Use `this.$watch` instead of `$scope.$watch` with 'Controller As'

后端 未结 4 1795
Happy的楠姐
Happy的楠姐 2021-02-20 06:44

Currently I am using the Controller As format for scoping controllers.

This works great for keeping the scope of values on the views clear and easy to follo

4条回答
  •  自闭症患者
    2021-02-20 07:28

    Others written clearly about why $scope is generally still required. But not how to actually watch your variables in the case of your example to properly watch the local variable "contacts" you must identify it by the controller namespace.

    So:

    $scope.$watch('myctrl.contacts', function(newValue, oldValue) {
           console.log({older: oldValue, newer:newValue});
        });
    

    The idea of using the local namespace is to prevent mutation if you create child controllers inside another controller. The nice benefit of this is that a parent controller can watch all the spaces inside its scope.

    Lets say that the initial html looked something like:

    and the js:

    angular.module('myApp',[])
    .controller('myController',['$scope',function(contacts) {
    
        $scope.$watch('mylist.contacts', function(newValue, oldValue) {
           console.log({older: oldValue, newer:newValue});
        })
    .controller('listController',['contacts',function(contacts) {
        this.contacts = contacts;
        });
    }]);
    

    Now the main controller is watching activity in a nested controller... pretty nifty.

提交回复
热议问题