在angularjs中渲染锚点后调用回调函数

时间:2016-02-05 07:02:17

标签: angularjs angularjs-directive

我的布局中有以下HTML:

<div class="icon-grid">

<a ng-if="udtTable.config.moreActionIcons" ng-repeat="mai in udtTable.config.moreActionIcons" 
ng-attr-data-toggle="{{(mai.modal) ? \'modal\' : undefined}}" 
ng-attr-data-target="{{(mai.modalName && mai.modal) ? mai.modalName : undefined}}"  
after-render="{{mai.callback}}"
href="{{mai.action}}/{{value.data.id}}" 
title="{{mai.tooltip}}">

<span class="{{mai.icon}}"></span>

</a>

</div>

这是我的after-render指令:

angular.module('neogetDataTableServices').directive('afterRender', ['$timeout', function ($timeout) {
    var def = {
        restrict: 'A',
        terminal: true,
        transclude: false,
        link: function (scope, element, attrs) {
            console.log(attrs.afterRender);
        }
    };
    return def;
}]);

我的目标是重复

var udtTable = {
  config: {
     "moreActionIcons" : [
            {
                "action": 'myaction.php',
                "icon": "icomoon-lock-open",
                "modal": true,
                "modalName": "#mkjax-modal",
                "tooltip":"Authorize",
                "callback": function() {
                    alert('hey rendered');
                }
            },
     ]
  }
}

现在问题是如果我写这行

after-render="helloworld"

然后我的指令after-render通过console.log(attrs.afterRender);

正确记录

但如果我写下面的内容如下:

after-render="{{mai.callback}}"

然后该指令不记录function() { alert('hey rendered'); }它表示它是一个空字符串。

有人有解决方案吗?

2 个答案:

答案 0 :(得分:0)

试试这样:

angular.module('neogetDataTableServices').directive('afterRender', ['$timeout', function ($timeout) {
    var def = {
        restrict: 'A',
        terminal: true,
        transclude: false,
        link: function (scope, element, attrs) {
            scope.$eval(attrs.afterRender);
        }
    };
    return def;
}]);

在html中:

after-render="mai.callback()"

答案 1 :(得分:0)

最好使用隔离的scope

angular.module('neogetDataTableServices').directive('afterRender', ['$timeout', function ($timeout) {
var def = {
    restrict: 'A',
    terminal: true,
    transclude: false,
    scope:{
      afterRender:"&"
    },
    link: function (scope, element, attrs) {
        console.log(scope.afterRender);
    }
};
return def;}]);

在这种情况下,angular将属性解释为函数。

in html

after-render="mai.callback()"