Angularjs: 'controller as syntax' and $watch

前端 未结 10 1583
抹茶落季
抹茶落季 2020-11-28 18:52

How to subscribe on property change when using controller as syntax?

controller(\'TestCtrl\', function ($         


        
10条回答
  •  长情又很酷
    2020-11-28 19:41

    Similar to using the "test" from "TestCtrl as test", as described in another answer, you can assign "self" your scope:

    controller('TestCtrl', function($scope){
        var self = this;
        $scope.self = self;
    
        self.name = 'max';
        self.changeName = function(){
                self.name = new Date();
            }
    
        $scope.$watch("self.name",function(value){
                console.log(value)
            });
    })
    

    In this way, you are not tied to the name specified in the DOM ("TestCtrl as test") and you also avoid the need to .bind(this) to a function.

    ...for use with the original html specified:

    
    

提交回复
热议问题