2015-12-08 116 views
0

我無法弄清楚如何在angularjs中觀察綁定到此變量的變量。如何在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?

在此先感謝

+1

當你將_controllerName作爲vm_添加到當前作用域屬性_vm_中時,你可以使用字符串'$ scope。$ watch('vm.text')' – Grundy

回答

2

您需要先綁定使用angular.bind

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

或場所內的觀察者,而不是字符串&將得到每個評價消化週期

功能 this上下文的角度 $scope
$scope.$watch(function() { 
    return vm.text; 
},function(value){ 
    console.log('watch 1'); 
    this.count=this.count+1; 
}); 
+0

如果我有兩個或多個要單獨觀察的變量,我會怎麼做呢? – MaheshKumar

+0

@MaheSirius如果你想分開看,那麼你應該有不同的觀察者。但是如果你想在單個wathc上觀看不同的值,你可以使用'$ watchGroup/$ watchCollection' –

0

你在這裏得到了一些獨立的擔憂。

您正在使用$ 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;  
}); 

這是一個有趣的情況,其中的範圍可以幫助不僅通過使手錶順利callable,而且也容易從我引用nside watch功能($ scope.watch)。