我试图从一个指令内部角度观察控制器的$ viewValue。
小提琴: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);
- });
- }
- }
- });
就这样,$ watch功能没有捕捉到在控制器内部2秒钟之后完成的模型更改。我失踪了什么
$ watch接受在该范围内要观看的属性的“名称”,您要求它观看该值。更改它来观看attrs.ngModel,返回“bar”,现在你正在观看scope.bar。您可以以相同的方式获取该值,或者使用范围[attrs.ngModel],这就是说scope [“bar”]再次与scope.bar相同。
- scope.$watch(attrs.ngModel,function(newValue) {
- console.log("Changed to " + newValue);
- });
要澄清user271996的注释:scope。使用$ eval是因为可以将对象符号传递到ng-model属性中。即ng-model =“someObj.someProperty”,因为scope [“someObj.someProperty”]无效,因此将无法正常工作。范围。$ eval用于将该字符串评估为实际对象,以便scope [“someObj.someProperty”]变为scope.someObj.someProperty。