javascript - Angular Watch 不适用于controllerAs 语法

标签 javascript angularjs watch angularjs-controlleras

观看响应时遇到问题。

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

<input  type="text" class="form-control" ng-model="settings.test.one"  />
<input  type="text" class="form-control" ng-model="settings.test.second"  />

这是我的 Controller :

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);
    });
  
  });

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

**** 仅在第一次时进行监视,当加载 Controller 并且我看到控制台日志时,但是当我尝试进行更改时,观察者什么也不做。

我做错了什么?

最佳答案

如果我没记错的话,你的 $watch 会在第一次加载 Controller 时被命中,但当你更改对象中的某些内容时不会被命中。如果这是真的,请尝试以下操作:

$scope.$watch('vm', function (newVal, oldVal) {
    console.log('newVal, oldVal', newVal, oldVal);
}, true);

默认情况下,$watch 函数监视引用,因此如果您仅更改监视对象的属性,则不会触发该函数。通过在末尾添加 true,您就可以开始深入观察,并且每次更改对象的属性时都会得到提示。

关于javascript - Angular Watch 不适用于controllerAs 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37830772/

相关文章:

javascript - ionic 重定向到主页不起作用

javascript - 如何使用 AngularJS ui-date 指令格式化初始日期值?

vue.js - vue组件数据看外面

file - FSNotify 在运行时添加监视目录

javascript - 在 JavaScript 中添加对象属性

javascript - 如何为事件监听器实现去抖动?存储事件问题

prototype - javascript 库原型(prototype)函数没有一个接一个地执行

javascript - 将php数组转换为js selectpicker数组格式

javascript - JS - onkeypress 不断将文本附加到末尾

java - 如何设置变量值并从 Netbeans 中的变量值开始运行?