我从我写过的自定义指令中得到了这个错误:
Error: [$compile:nonassign] http://errors.angularjs.org/1.2.16/$compile/nonassign?p0=&p1=fileUpload
at Error (native)
(anonymous function) angular.js:9778
(anonymous function) angular.js:7216
h.$digest angular.js:12270
h.$apply angular.js:12516
oFReader.onload file-upload.js:81
file-upload.js(oFReader.onload file-upload.js:81)第81行的指令代码是:
scope.fileUploadImage = attachment;
scope.fileUploadLoading = false;
scope.$apply(); //line 81
scope.fileUploadCallback();
以下是我在视图文件中调用该指令的位置:
<div file-upload
file-upload-image="fileAttachment"
file-upload-loading=""
file-upload-error="errors"
file-upload-limit="1048576"
file-upload-callback="attachFile()"
class="field">
代码作为例外工作,但我似乎无法摆脱这个错误。有什么帮助吗?
答案 0 :(得分:3)
AngularJS中显示的链接可以actually go to,在这种情况下,当您转到错误说明页面时,它会说
表达&#39;&#39;用于指令&#39; fileUpload&#39;是不可转让的!
该指令正在进行
scope.fileUploadLoading = false;
但是,您没有将范围变量传递给file-upload-loading
属性:
file-upload-loading=""
这意味着它在指令中分配值,然后应用更改,AngularJS发现更改并执行双向数据绑定,但发现它无处存储false
值,因为没有变量是在属性上给出的。实际上,它试图将虚假分配给任何东西。
如何清除错误消息,可以添加一些未使用的属性:
file-upload-loading="iDontEvenUseThis"
从来没有看过它,或者指令可能允许你完全省略属性,这取决于指令的实现。
答案 1 :(得分:0)
另一种选择是检查你的指令是否在分配之前分配了一个值。
/**
* Checks whether an attribute of a directive is defined and can be assigned a value.
* This is important for optional attributes in order to avoid the 'Non-assignable' angular error
* @param {object} attrs The attrs object retrieved in the directive link function
* @param {string} propertyName The name of the property to check
* @return {Boolean} True means that property is assignable
*/
function isAssignable(attrs, propertyName) {
var fn = $parse(attrs[propertyName]);
return angular.isFunction(fn.assign);
}
使用示例:
.directive('yourDirectiveName', function() {
return {
scope: {
fileUploadLoading: "=",
...
},
link: function($scope, element, attrs) {
...
if(isAssignable(attrs, 'fileUploadLoading')) {
$scope.fileUploadLoading = newValue;
}
}
};
});
希望它有所帮助。