Dus*_*tin 54 javascript angularjs angularjs-directive
我试图从我的链接功能中查看我的模型值.
scope.$watch(attrs.ngModel, function() {
console.log("Changed");
});
Run Code Online (Sandbox Code Playgroud)
当我更改控制器内的模型值时,不会触发$ watch函数.
$scope.myModel = "ACT";
$timeout(function() {
$scope.myModel = "TOTALS";
}, 2000);
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/dkrotts/BtrZH/4/
我在这里错过了什么?
Ben*_*esh 149
您需要观看一个返回您正在观看的$ 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);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
dnc*_*253 31
问题是,你$watch荷兰国际集团attrs.ngModel等于"基于myModel".您的范围中没有绑定"myModel".你想$watch"模仿".这就是你的指令范围内的约束.见http://jsfiddle.net/BtrZH/5/
Emm*_*uel 20
正确的方法是:
app.directive('myDirective', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function () {
var newValue = ngModel.$viewValue;
console.log(newValue)
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
小智 8
这是另一种方法:
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);
});
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
这样做,你就可以通过这样的绑定来听取价值变化
| 归档时间: |
|
| 查看次数: |
80615 次 |
| 最近记录: |