![](/img/trans.png)
[英]$watch for value change from inside angular directive when using isolate scope
[英]$watch ngModel from inside directive using isolate scope
我試圖從我的鏈接功能中查看我的模型值。
scope.$watch(attrs.ngModel, function() {
console.log("Changed");
});
當我更改控制器內的模型值時,不會觸發$ watch函數。
$scope.myModel = "ACT";
$timeout(function() {
$scope.myModel = "TOTALS";
}, 2000);
小提琴: http : //jsfiddle.net/dkrotts/BtrZH/4/
我在這里錯過了什么?
您需要觀看一個返回您正在觀看的$ modelValue的函數。
以下代碼顯示了一個基本示例:
app.directive('myDirective', function (){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
console.log(newValue);
});
}
};
});
問題是你要$watch
attrs.ngModel
,它等於“myModel”。 您的范圍中沒有綁定“myModel”。 你想$watch
“模特”。 這就是你的指令范圍內的約束。 見http://jsfiddle.net/BtrZH/5/
正確的方法是:
app.directive('myDirective', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function () {
var newValue = ngModel.$viewValue;
console.log(newValue)
};
}
};
});
這是另一種方法:
app.directive('myDirective', function (){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
attrs.$observe('ngModel', function(value){ // Got ng-model bind path here
scope.$watch(value,function(newValue){ // Watch given path for changes
console.log(newValue);
});
});
}
};
});
這樣做,你就可以通過這樣的綁定來聽取價值變化
這是@ Emmanuel上面回答@Martin Velez的答案的擴展,雖然我知道它已經很晚了! (我還不能發表評論,所以如果這不是正確的地方,對不起!)
我不確定哪個版本的Angular OP正在使用,但在Angular#1.2 +中至少在官方文檔https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$render,$ render列出如下:
在需要更新視圖時調用。 預計ng-model指令的用戶將實現此方法。
在以下情況下調用$ render()方法:
$ rollbackViewValue()被調用。 如果我們將視圖值回滾到最后提交的值,則調用$ render()來更新輸入控件。 ng-model引用的值以編程方式更改,$ modelValue和$ viewValue與上次不同。 由於ng-model不進行深度監視,因此只有$ modelValue和$ viewValue的值實際上與之前的值不同時才會調用$ render()。
我認為這意味着從指令中觀察ngModel的正確方法是要求ngModel並實現注入ngModelController的鏈接函數。 然后使用內置於$ render-on-change($ watch)或其他任何內容的ngModel API。
有兩種方法可以做到這一點。
1)你可以使用$attrs.[any_attribute]
並在其上設置任何監聽器
2)你可以使用2種方式綁定變量的隔離范圍並在其上設置一個監聽器。如果你想要更多,這里有一篇很酷的文章
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.