从内部指令观察控制器模型值 [英] Watch controller model value from inside directive

查看:22
本文介绍了从内部指令观察控制器模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从指令内部角度观察控制器的 $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);
            });
        }
    } 
});

照原样,$watch 函数没有从控制器内部捕获 2 秒后完成的模型更改.我错过了什么?

As is, the $watch function is not catching the model change done after 2 seconds from inside the controller. What am I missing?

推荐答案

$watch 接受要在范围内监视的属性的名称",您要求它监视值.将其更改为 watch attrs.ngModel 返回bar",现在您正在观看 scope.bar.您可以像以前一样获取值,也可以使用 scope[attrs.ngModel] ,这就像说 scope["bar"] 一样,与 scope["bar"] 相同代码>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 的评论:使用 scope.$eval 是因为您可以将对象符号传递到 ng-model 属性中.即 ng-model="someObj.someProperty" 不起作用,因为 scope["someObj.someProperty"] 无效.scope.$eval 用于将该字符串评估为实际对象,以便 scope["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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆