好奇"编译" angularjs指令中的函数

时间:2014-06-21 16:23:37

标签: angularjs angularjs-directive directive

完整代码位于here of plunker

当我删除编译:函数(tElement,tAttrs,transclude)函数时,功能正常

app.directive('whatIsInThese', ['$compile', function($compile) {
return {
    restrict: 'A',
 compile: function (tElement, tAttrs, transclude) {
       // this compile function is very curious and hard to explain
       // i have do nothing here
    },
 link: function(scope, elem, attrs) {
     scope.getTestUrl = function() {
        return "test.html";
     };
    var these = attrs.whatIsInThese.split(' ');
    var html = '<div ng-include src="getTestUrl()"></div>';
    var el = angular.element(html);
    var compiled = $compile(el);
    elem.append(el);
    compiled(scope);
}
};
}]);

任何人都可以解释为什么会发生这种情况吗?

1 个答案:

答案 0 :(得分:1)

正如AngularJS

的文档中所述
  

编译函数处理转换模板DOM。[...]   仅当未定义编译属性时才使用link属性。

所以这个:

link: function (scope, elem, attrs) {
    scope.getTestUrl = function () {
        return "test.html";
    };
    var these = attrs.whatIsInThese.split(' ');
    var html = '<div ng-include src="getTestUrl()"></div>';
    var el = angular.element(html);
    var compiled = $compile(el);
    elem.append(el);
    compiled(scope);
}

相同
compile: function (tElement, tAttrs, transclude) {
    return function (scope, elem, attrs) {
        scope.getTestUrl = function () {
            return "test.html";
        };
        var these = attrs.whatIsInThese.split(' ');
        var html = '<div ng-include src="getTestUrl()"></div>';
        var el = angular.element(html);
        var compiled = $compile(el);
        elem.append(el);
        compiled(scope);
    }
};