javascript - Angularjs: 'controller as syntax' 和 $watch

标签 javascript angularjs angularjs-scope ng-controller

使用 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>  

最佳答案

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

$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 与正确的上下文绑定(bind)。但是,我发现他的答案更清晰。

话虽如此,首先,您必须了解the underlying idea behind it .

更新 2:

对于那些使用 ES6 的人,通过使用 箭头函数,您可以获得具有正确上下文 OOTB 的函数。

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

Example

关于javascript - Angularjs: 'controller as syntax' 和 $watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24078535/

相关文章:

AngularJS 代码理解

javascript - 如何在 Javascript 中轻松组合两个数组中的元素,交替元素?

javascript - 防止在自定义日期选择器中手动输入

javascript - 将按钮移出容器时,单击时克隆 div 会中断吗?

javascript - browserify 与 Angular : cannot add restangular dependency

javascript - 限制 AngularJS 中的 $scope

javascript - 仅当已选中时才单击复选框

javascript - AngularJs 解构 $location

javascript - 在 ng-repeat 中使用 ng-if 和 ng-switch 失败

javascript - 当属性改变时$watch的对象不被触发