Angularjs: 'controller as syntax' and $watch

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

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

controller(\'TestCtrl\', function ($         


        
10条回答
  •  天命终不由人
    2020-11-28 19:46

    Just bind the relevant context.

    $scope.$watch(angular.bind(this, function () {
      return this.name;
    }), function (newVal) {
      console.log('Name changed to ' + newVal);
    });
    

    Example: http://jsbin.com/yinadoce/1/edit

    UPDATE:

    Bogdan Gersak's answer is actually kind of equivalent, both answers try binding this with the right context. However, I found his answer cleaner.

    Having that said, first and foremost, you have to understand the underlying idea behind it.

    UPDATE 2:

    For those who use ES6, by using arrow function you get a function with the right context OOTB.

    $scope.$watch(() => this.name, function (newVal) {
      console.log('Name changed to ' + newVal);
    });
    

    Example

提交回复
热议问题