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

后端 未结 4 1722
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:20

    Even with the controllerAs format, the $scope is there.

    In fact what controllerAs does is bind the controller instance's this to the $scope.
    E.g. controller="myController as myctrl" does (behind the scenes): $scope.myctrl = this (where this refers to the myController instance).

    So, you can just inject and use the $scope for watches:

    .controller('myController', function ($scope, contacts) {
        this.contacts = contacts;
    
        $scope.$watch(function () {
            return contacts;
        }, function (newValue, oldValue) {...});
    });
    

提交回复
热议问题