Search code examples
javascriptangularjsangularjs-directiveangularjs-watch

$watch not being fired


I am using code from an AngularJS implementation of ScrollSpy (original article here) but have ran into a problem when my navigation is dynamically created, but it does work when the navigation is statically created.

So I have a scrollSpy directive that watches a list of spies. The spies list is basically a list of the navigational elements it should highlight as the user scrolls through a page. spies are added via an addSpy method in the scrollSpy controller like so

controller: function ($scope) {
    $scope.spies = [];
    return this.addSpy = function (spyObj) {
        return $scope.spies.push(spyObj);
    };
},

The addSpy function always gets called, however when I add the spies dynamically the $watch for that list never gets fired, it does get fired when the navigational items are statically created.

link: function (scope, elem, attrs) {
    scope.$watch('spies', function (spies) {
        // I never get called when spies are added dynamically, even 
        // though spies are added to the $scope.spies object in the controller!
    }

Can anyone help me understand why the $watch isnt being fired? I tried adding $scope.$apply to it but it said it was already inside a digest cycle.


Solution

  • scope.$watch('spies', function (spies) {
        // I never get called when spies are added dynamically, even 
        // though spies are added to the $scope.spies object in the controller!
    }, true);
    

    You have to tack on ,true at the end as you're not changing the reference, just updating it.