Kuan
Kuan

Reputation: 11389

When do we need to manually watch scope variable and when not in AngularJS

All:

I am new to AngularJS directive, I got a question about monitoring scope variable which is:

I want to know when I should manually add scope.$watch, for example: I build a directive like

        app.directive("followerlist", function(){
            return {
                restrict: "AE",
                scope: {
                    fllws: "="
                },
                templateUrl: "tmpl/followerlist.html",
                controller: function(){

                },
                link: function(scope, EL, attrs){

                }
            }
        });

The template is like:

<ul>
<li ng-repeat="f in fllws">
    {{f.login}}
</li>
</ul>

And the html is like:

<body ng-controller="main">
    <followerlist fllws="followers"></followerlist>
</body>

In this way, I do not need to manually register any watcher but still can respond to the data change (if I change $scope.followers in main controller, the list can change immediately )

I thought I should manually watch the change for external and internal variable(sometime the change will not get respond unless I manually register watcher), I wonder if anyone could give me some summary about when I should manually watch and when I do not need to?

Thanks

Upvotes: 2

Views: 564

Answers (1)

Michael Benford
Michael Benford

Reputation: 14104

Your code works without manually creating a watch because Angular did that for you when you bound the fllws property to your template. Angular automatically does that for every binding unless you use a one-time binding.

You should manually create a watch every time you need to perform some action when the model changes or a condition becomes true. This answer contains more technical information about it.

Upvotes: 2

Related Questions