javascript $watch 在范围内更新模型时不起作用。 $apply in 指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12762666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$watch is not working when model is updated in scope.$apply in directive
提问by Abdul Azeez
i have a directive where i have added a watch on the 'existingfiles' model of the directive scope. When there is change in the model through scope.$apply, there is no call to listener in watch.
我有一个指令,我在指令范围的“现有文件”模型上添加了一个监视。当模型通过scope.$apply发生变化时,watch中不会调用listener。
Here is the directive code, kindly let me know if i am missing something here,
这是指令代码,如果我在这里遗漏了什么,请告诉我,
directive('fileuploadPlugin', function() {
var linkFn;
linkFn = function(scope, element, attrs) {
angular.element(element).ready(function() {
jQuery('#fileupload').fileupload({
done: function (e, data) {
scope.$apply(function(scope) {
for(var i=0; i < data.result.filesuploaded.length; i++){
scope.existingfiles.push(data.result.filesuploaded[i]);
};
});
}
});
scope.$watch('existingfiles', function(newValue, oldValue) {
element.imagesLoaded(function() {
scope.$apply( function() {
element.masonry({
itemSelector : '.box'
});
});
});
});
};
return {
templateUrl : 'templates/fileupload_plugin.htm',
restrict : 'A',
scope : {
existingfiles : '=ngModel',
},
link : linkFn
};
})
Here is my call to directive,
这是我对指令的调用,
<div fileupload-plugin ng-model="existingfiles"></div>
Kindly let me know how to make sure that model is watched properly
请让我知道如何确保正确观看模型
回答by Abdul Azeez
Problem has been resolved by giving 'true' as third parameter of $watch call. Please find here, the more information on third parameter,
问题已通过将 'true' 作为 $watch 调用的第三个参数解决。请在这里找到关于第三个参数的更多信息,