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

Abdul Azeez picture Abdul Azeez · Oct 6, 2012 · Viewed 19.1k times · Source

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

Answer

Abdul Azeez picture Abdul Azeez · Oct 7, 2012

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