Angularjs:“controller as syntax”和$watch

使用语法时如何订阅属性更改?controller as

controller('TestCtrl', function ($scope) {
  this.name = 'Max';
  this.changeName = function () {
    this.name = new Date();
  }
  // not working       
  $scope.$watch("name",function(value){
    console.log(value)
  });
});
<div ng-controller="TestCtrl as test">
  <input type="text" ng-model="test.name" />
  <a ng-click="test.changeName()" href="#">Change Name</a>
</div>  

答案 1

只需绑定相关上下文即可。

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

示例:http://jsbin.com/yinadoce/1/edit

更新:

Bogdan Gersak的答案实际上是等价的,两个答案都试图与正确的上下文绑定。但是,我发现他的答案更干净。this

话虽如此,首先,你必须了解它背后的基本思想

更新 2:

对于那些使用ES6的人来说,通过使用,你可以得到一个具有正确上下文OOTB的函数。arrow function

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


答案 2

我通常这样做:

controller('TestCtrl', function ($scope) {
    var self = this;

    this.name = 'Max';
    this.changeName = function () {
        this.name = new Date();
   }

   $scope.$watch(function () {
       return self.name;
   },function(value){
        console.log(value)
   });
});