观看里面的指令控制器模型值 [英] Watch controller model value from inside directive
问题描述
我想有角的手表 $ viewValue
控制器从指令中。
I am trying to have angular watch the $viewValue
of a controller from inside a directive.
提琴: http://jsfiddle.net/dkrotts/TfTr5/5/
function foo($scope, $timeout) {
$scope.bar = "Lorem ipsum";
$timeout(function() {
$scope.bar = "Dolor sit amet";
}, 2000);
}
myApp.directive('myDirective', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, controller) {
scope.$watch(controller.$viewValue, function() {
console.log("Changed to " + controller.$viewValue);
});
}
}
});
由于是在$手表功能不捕后2秒完成从控制器内的模式变革。我缺少什么?
As is, the $watch function is not catching the model change done after 2 seconds from inside the controller. What am I missing?
推荐答案
$观看
接受的范围内观看属性的名,你问它来观看的价值。将其更改为观看 attrs.ngModel
返回栏,现在你看 scope.bar
。你可以得到价值以同样的方式你也可以使用范围[attrs.ngModel]
这好像是说的范围[条]
这又是一样的 scope.bar
。
$watch
accepts the "name" of the property to watch in the scope, you're asking it to watch the value. Change it to watch attrs.ngModel
which returns "bar", now you're watching scope.bar
. You can get the value the same way you were or use scope[attrs.ngModel]
which is like saying scope["bar"]
which again, is the same as scope.bar
.
scope.$watch(attrs.ngModel, function(newValue) {
console.log("Changed to " + newValue);
});
要澄清user271996的评论:范围$ EVAL
的使用,因为你可以把对象标记成 NG-模型
属性。即 NG-模式=someObj.someProperty
这不会起作用,因为的范围[someObj.someProperty]
是无效的。 范围。$ EVAL
用于该字符串评估为实际的对象,这样的范围[someObj.someProperty]
成为 scope.someObj.someProperty
。
To clarify user271996's comment: scope.$eval
is used because you may pass object notation into the ng-model
attribute. i.e. ng-model="someObj.someProperty"
which won't work because scope["someObj.someProperty"]
is not valid. scope.$eval
is used to evaluate that string into an actual object so that scope["someObj.someProperty"]
becomes scope.someObj.someProperty
.
这篇关于观看里面的指令控制器模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!