在指令中调用控制器方法适用于范围,但不适用于attrs?

时间:2017-02-15 08:33:56

标签: angularjs directive

我想在指令完成DOM中的更改之后调用控制器的方法,但它不起作用,所以我在指令中发送该方法,该方法在scope.$watch

内调用
.directive('checkThis', function($timeout) {
    return {
        restrict: 'E',
        scope: {
            myData: '=',
            dirty: '=',
            what: '@',
            callback: '&'
        },
        link: function(scope, element, attrs) {
            scope.$watch('myData', function(newValue, oldValue) {
                if (newValue !== oldValue) {
                    if (newValue) {
                        scope.dirty++;
                    } else { 
                        scope.dirty--;
                    }
                    check();
                }
            });

            var check = function () {
                if (angular.isDefined(scope.callback)) {
                    $timeout(function() {
                        console.log('being called');
                        scope.callback();
                    }, 0, false);
                }
            };
        }
    };
});

并在HTML中使用此指令,如下所示

<check-this my-data="vm.encryption" dirty="vm.dirty" what="column" callback="vm.checkAll()"></check-this>

现在,当我使用attrs.callback时,它没有被执行但是scope.callback()被执行,即使我检查attrs.callback它在控制台中显示方法。

为什么会出现这种情况?

即使我尝试了scope.$eval(attrs.callback)

 scope.$apply(function() { 
    scope.$eval(attrs.callback); 
 });

但它没有被调用。我正在参考this article

1 个答案:

答案 0 :(得分:0)

Angular directive attrs are strings, so calling attrs.callback is the string 'vm.checkAll()' in your example. Using $eval can work but it is not recommended as it can be harmful to your application's security.

The solution is to use scope.callback(), is there some reason you don't want to use that?

If for some reason you absolutely need to use attrs.callback, you can use scope.$parent.$eval(attrs.callback); or eval('scope.$parent.' + attrs.callback), because these will evaluate vm.checkAll() in the parent scope.

scope.$eval(attrs.callback) will not work because your directive is using isolate scope.