在AngularJS指令中观察函数的值

Watching the value of function in an AngularJS directive

本文关键字:函数 观察 AngularJS 指令      更新时间:2023-09-26

是否有一种方法可以观察AngularJS指令中函数表达式的值变化?我有以下HTML和JavaScript,模板中{{editable()}}的插值显示值为true,而在Chrome中检查HTML元素显示contenteditable为false。

有什么建议,我怎么能看到这个函数的值的变化,并相应地更新元素attr ?或者是否有更好的方法来实现这一点?(我仍然想计算这个函数)

HTML:

<h4 editable="account.hasRole('ROLE_ADMIN')" content="doc.heading"></h4>
Javascript:

mod
    .directive(
            'editable',
            function() {
                return {
                    restrict : 'A',
                    template : '<button class="btn pull-right"><i class="icon-pencil"></i></button>{{content}} ({{editable()}})',
                    scope : {
                        'content' : '=',
                        'editable' : '&'
                    },
                    link : function(scope, element, attrs) {
                        scope.$watch('editable', function(newValue) {
                            element.attr('contenteditable', newValue());
                        });
                    }
                };
            });

试着把手表放在'editable()'而不是'editable'

解释:需要这样做的原因是'&'指向属性表达式动态生成的函数包装器,而不是表达式本身。这个特殊的包装函数返回account.hasRole('ROLE_ADMIN')的值。

我也希望这样做:

scope.$watch(function () {
  return scope.editable();
}, function (val) {
   // ...
});