Angular watch不适用于controllerAs语法

Dar*_*hJS 0 javascript watch angularjs angularjs-controlleras

观看回复时遇到问题.

我有一个SettingsCtrl作为设置,这是我的观点:

<input  type="text" class="form-control" ng-model="settings.test.one"  />
<input  type="text" class="form-control" ng-model="settings.test.second"  />
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {
  
  var vm = this;
  
  
  settingsFactory.test().then(function(response){
  
     vm.test = response;
  })
  
  /////  OR
  
  vm.test = Test; // this is from ui-router resolve
  
  
    $scope.$watch(angular.bind('vm', function () {
    return vm.test;
    }), function (newV, oldV) {
    console.log(newV, oldV); 
    });
  
    $scope.$watch(function watch(scope){
     return vm.test;
    }), function handle(newV, oldV) {
    console.log(newV, oldV);
    });
  
    $scope.$watch('vm', function (newVal, oldVal) {
        console.log('newVal, oldVal', newVal, oldVal);
    });
  
  });
Run Code Online (Sandbox Code Playgroud)

我一直在寻找并找到了不同的解决方案,但没有解决方案.

****它只是第一次观看,当控制器加载并且我看到我的控制台日志时,但是当我尝试进行更改时,观察者什么都不做.

我做错了什么?

小智 8

如果我没错,你的$ watch会在第一次加载控制器时被击中,但是当你在对象中改变某些东西时却不会.如果这是真的,那么试试这个:

$scope.$watch('vm', function (newVal, oldVal) {
    console.log('newVal, oldVal', newVal, oldVal);
}, true);
Run Code Online (Sandbox Code Playgroud)

默认情况下,$ watch函数会监视引用,因此如果您只更改被监视对象的属性,则不会触发它.通过true在最后添加,您可以开始深入观察,每次更改对象的属性时都会遇到命中.