完整代码位于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);
}
};
}]);
任何人都可以解释为什么会发生这种情况吗?
答案 0 :(得分:1)
编译函数处理转换模板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);
}
};