当我使用angular 1.5.3进行编码时。 这是代码:模板和templateUrl在指令中的区别
app.js
var testApp = angular.module('test-app', ['plugin.template']);
testApp.run(function ($rootScope) {
});
createDirective('directiveOne');
createDirective('directiveTwo');
createDirective('directiveThree');
function createDirective(name) {
testApp.directive(name, function() {
return {
template: '<div>Hello<div ng-transclude></div></div>',
// templateUrl: 'template.html',
transclude: true,
replace: true,
compile: function (element, attr) {
console.log(name + '指令的compile...');
return {
post: function (iScope, iElm, iAttr, ctrl) {
console.log(name + '指令的postlink...');
},
pre: function() {
console.log(name + '指令的prelink...');
}
}
}
}
});
}
插件,template.js
(function (app) {
try {
app = angular.module("plugin.template");
}
catch (err) {
app = angular.module("plugin.template", []);
}
app.run(["$templateCache", function ($templateCache) {
"use strict";
$templateCache.put("template.html", "<div>hello<div ng-transclude></div></div>");
}]);
})();
的index.html
<!DOCTYPE html>
<html lang="zh" ng-app="test-app">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, minimum-scale=1.0,initial-scale=1, maximum-scale=1.0, user-scalable=no">
<script src="../dist/js/angular/angular.js"></script>
<script src="plugin-template.js"></script>
<script src="app.js"></script>
</head>
<body>
<directive-one>
<directive-two>
<directive-three>
</directive-three>
</directive-two>
</directive-one>
</body>
</html>
在功能createDirective
,当注释掉// templateUrl: 'template.html',
。
template: '<div>Hello<div ng-transclude></div></div>',
// templateUrl: 'template.html',
transclude: true,
replace: true,
这里的日志:
directiveOne指令的compile...
directiveOne指令的prelink...
directiveTwo指令的compile...
directiveTwo指令的prelink...
directiveThree指令的compile...
directiveThree指令的prelink...
directiveThree指令的postlink...
directiveTwo指令的postlink...
directiveOne指令的postlink...
当注释掉// template: '<div>Hello<div ng-transclude></div></div>',
// template: '<div>Hello<div ng-transclude></div></div>',
templateUrl: 'template.html',
transclude: true,
replace: true,
这里的日志:
directiveOne指令的compile...
directiveOne指令的prelink...
directiveOne指令的postlink...
directiveTwo指令的compile...
directiveTwo指令的prelink...
directiveTwo指令的postlink...
directiveThree指令的compile...
directiveThree指令的prelink...
directiveThree指令的postlink...
当注释掉所有为:
// template: '<div>Hello<div ng-transclude></div></div>',
// templateUrl: 'template.html',
// transclude: true,
// replace: true,
这里的日志:
directiveOne指令的compile...
directiveTwo指令的compile...
directiveThree指令的compile...
directiveOne指令的prelink...
directiveTwo指令的prelink...
directiveThree指令的prelink...
directiveThree指令的postlink...
directiveTwo指令的postlink...
directiveOne指令的postlink...
的“编译”,“预链接”,“postlink”的顺序改变,当我注释掉一些代码如上。
这是为什么? 你能解释模板和templateUrl之间的不同,以及使用transclude和不使用transclude之间的差异吗? 非常感谢。
因此,它是在指令该容器中的任何其他指令使用templateUrl一个unrecoment方式? – timShadow