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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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

Answers:

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