$watch is not working when model is updated in scope.$apply in directive

蓝咒 提交于 2019-12-04 10:29:10

问题


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.

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


回答1:


Problem has been resolved by giving 'true' as third parameter of $watch call. Please find here, the more information on third parameter,

Angular Docs on $rootScope



来源:https://stackoverflow.com/questions/12762666/watch-is-not-working-when-model-is-updated-in-scope-apply-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!