【问题标题】:How to watch this variable in angularjs如何在angularjs中观察这个变量
【发布时间】:2016-03-13 21:59:06
【问题描述】:

我不知道如何在 angularjs 中查看绑定到该变量的变量。

这是我尝试过的。

在 HTML 中,

<input type="text" ng-model="vm.text"/>--{{vm.text}}--
    <p>{{vm.count}} times changed</p>
    <input type="text" ng-model="text1"/>--{{text1}}--
    <p>{{count1}} times changed</p>

在 app.js 中

$scope.$watch('this.text', function() {
    console.log('watch 1');
    this.count=this.count+1;
});

$scope.$watch('text1', function() {
// do something here
   console.log('watch 2');
   $scope.count1=$scope.count1+1;
});

和 plunker link 相同。

我可以看 text1 但我不能看 text1。

谁能解释一下如何观看text1?

提前致谢

【问题讨论】:

  • 当您执行 controllerName as vm 时,您将添加到当前范围属性 vm,因此您可以使用字符串 $scope.$watch('vm.text')

标签: javascript angularjs watch angularjs-controlleras


【解决方案1】:

您需要首先使用angular.bindthis 上下文绑定到角度$scope

$scope.$watch(angular.bind(this, function () {
  return this.text;
}), function (newVal) {
  console.log('watch 1');
  this.count=this.count+1;
});

或者在 watcher 中放置一个函数而不是字符串 & ,它将在每个摘要循环中进行评估

$scope.$watch(function () {
   return vm.text;
},function(value){
   console.log('watch 1');
   this.count=this.count+1;
});

【讨论】:

  • 如果我有两个或多个变量要单独观察,我该怎么做?
  • @MaheSirius 如果您想单独观看,那么您应该有不同的观看者。但如果你想在单个 wathc 上观看不同的值,你可以$watchGroup/$watchCollection
【解决方案2】:

你需要看vm.text

http://plnkr.co/edit/ctDjs0dwe50kMu61TfCW?p=preview

$scope.$watch('vm.text', function() {
       console.log('watch 1');
             this.count=this.count+1;

   });

【讨论】:

    【解决方案3】:

    您在这里有一些单独的问题。

    您正在使用带有控制器的 $scope.watch 作为语法。这不是一个简单的文字,这里有一个很好的文字:

    http://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm

    这是我的你的 plunker 的叉子:

    http://plnkr.co/edit/ctDjs0dwe50kMu61TfCW?p=preview

    我所做的是:

    /*make this (controller) callable 
     *from inside my watch function, 
     *so I can observe it and count can change
     */
    var vm = this; 
    
    //vm is observable as it is assigned
    $scope.$watch(function (scope) {return vm.text;}, 
    
    
    function() {
       console.log('watch 1');
      //count can change, as the controller is assigned to variable
       vm.count=vm.count+1;       
    });
    

    这是一个有趣的情况,在这种情况下,作用域不仅可以通过使 watch 可以顺利调用,而且还可以从 watch 函数 ($scope.watch) 内部轻松引用。

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 2015-11-20
      • 2017-12-03
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 2014-02-15
      相关资源
      最近更新 更多