我有以下 html,我可以告诉您通过单独的“附件”指令清楚地描述了每个属性值。这些值位于该指令的 attrs 列表中,该指令位于模式文件上传表单上。
<p>For Testing Purpose: Attachment Type: {{attachCtrl.attributes.attachmentType}}</p>
<p>For Testing Purpose: CK ID: {{attachCtrl.attributes.attachmentId}}</p>
附件指令
.directive('attachment', ['$modal', function ($modal) {
return {
restrict: 'E',
transclude: false,
replace: true,
template: '<a class="pull-right" href="#" ng-click="open()"><i class="fa fa-files-o fa-lg" style="padding-right: 5px"></i>Attachment</a>',
link: function (scope, elem, attrs, controller) {
scope.open = function () {
$modal.open({
templateUrl: root + 'AccountingModule/modal/attachment/attachment-modal.html',
size: 'md',
backdrop: true,
controller: ['attributes', function (attributes) {
var viewModel = this;
viewModel.attributes = attributes;
}],
controllerAs: 'attachCtrl',
resolve: {
attributes: function () { return attrs; }
}
});
}
}
}
}])
执行文件上传指令时,我尝试包含这两个属性,以便可以通过文件上传链接将它们作为参数发送。列表中只有 first 属性;第二个不是。如果我改变顺序,另一个属性就会在列表中。
html:
<button type="button" class="btn btn-default" file-upload
attachment-type="{{attachCtrl.attributes.attachmentType}}"
attachment-id="{{attachCtrl.attributes.attachmentId}}">
Upload
</button>
指令:
console.log('attachment type on file upload directive: ' + attrs.attachmentType)
console.log('attachment id on file upload directive: ' + attrs.attachmentId)
文件上传指令
.directive('fileUpload', ['$http', '$parse', function ($http, $parse) {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
//for testing purpose. need to be removed.
console.log('attachment type on file upload directive: ' + attrs.attachmentType)
console.log('attachment id on file upload directive: ' + attrs.attachmentId)
element.bind('click', function () {
// Create the formdata and get the file
var file = document.getElementById("inpFile").files[0];
var formdata = new FormData();
formdata.append('uploadedFile', file);
ajaxUrl = root + 'FileUpload/upload?' & 'Type=' & attrs.attachmentType & 'ID=' & attrs.attachmentId;
$http.post(ajaxUrl, formdata, {
headers: { "Content-Type": undefined }
})
.success(function (status) {
if (status.Succeed) {
alert('File Uploaded successfully.');
}
else {
alert(status.Err);
}
});
});
}
};
}])
我需要做什么才能成功包含这两个属性并将它们传递给指令,将它们都包含在属性列表中?
最佳答案
我不知道您在哪里使用附件指令,但您可以在文件上传指令的属性中设置 attachment-type
和 attachment-id
属性通过将以下 scope
对象添加到文件上传指令中来链接函数:
...
restrict: 'A',
scope: {
attachmentType: '@',
attachmentId: '@'
},
link: ...
现在文件上传指令将了解这些属性。这会在指令上创建一个隔离范围。 '@'
指定是字符串,因为我假设您将字符串传递给这些属性。这应该可以让你摆脱那个讨厌的插值并像这样写:
<button type="button" class="btn btn-default" file-upload attachment-type="attachCtrl.attributes.attachmentType" attachment-id="attachCtrl.attributes.attachmentId">Upload</button>
请仔细检查插值部分,我没有测试过。暨grano salis。
无论如何,您现在应该能够通过 scope.attachmentType
和 scope.attachmentId< 访问
。 Angular 会为你将破折号变成驼峰式大小写。link
函数中这两个属性的值
关于javascript - Angular Directive(指令)中无法访问多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529209/