编译隔离指令中的函数 - AngularJS

时间:2015-12-22 02:22:38

标签: javascript angularjs angularjs-directive compilation

我正在尝试理解如何从内置编译指令调用外部函数。 以下是一个示例:http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview

HTML:

<!DOCTYPE html>
<html ng-app="app">

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="script.js"></script>
    </head>

    <body ng-controller="myController as vm">

        <my-directive callback="vm.saveAction()" label="click me!"></my-directive>

    </body>

</html>

JS:

app = angular.module('app', []);

app.controller('myController', function() {
    var vm = this;

    vm.saveAction = function() {
        alert("foo!"); 
    }
});

app.directive('myDirective', function() {
    var directive = {
        restrict: 'E',
        scope: {
            callback: '&'
        },
        compile: compile,
        link: link
    };

    return directive;

    function compile(element, attrs) {
        var template = '<button ng-click="action()">'+attrs.label+'</button>';

        element.replaceWith(template);
    }

    function link(scope, element) {
        scope.action = function() {
            // ...something usefull to do...
            scope.callback();
        }
    }
});

我知道我可以通过链接函数轻松地完成它(并且它可以从那里开始工作),但我真的需要从编译方法中做到这一点(这只是一个简化版本以更好地指出问题)。 有人能帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用template指令执行此操作

app.directive('myDirective', function() {
var directive = {
    restrict: 'E',
    scope: {
        callback: '&',
        label: '@'
    },
    template: '<button ng-click="action()">{{label}}</button>',
    link: link
};

return directive;

function link(scope, element, attrs) {
    console.log(scope.label);
    scope.action = function() {
        // ...something usefull to do...
        scope.callback();
    }
}

});

或者如果您想使用编译方法,请使用pre或post方法并自行编译:

function compile(element, attrs) {
   return {
      pre: function(scope, elem, attrs) {
          var template = $compile('<button ng-click="action()">'+attrs.label+'</button>')(scope);

         element.replaceWith(template);
      },
      post: function (scope, elem, attrs) {
         // or here
      }
   }
}