在angularjs指令中'template'和'templateUrl'有什麼不同?AngularJS - 如何解釋輸出
的index.html:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<child-a-drtv></child-a-drtv>
<script src="angular.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js:
var app = angular.module('app', []);
app.directive('childADrtv', function() {
return {
restrict: 'E',
templateUrl: 'child-A-template.html',
//template: 'A<child-b-drtv></child-b-drtv>',
controller: function ($scope) {
console.log('childA Controller');
},
link: function() {
console.log('childA Link');
}
};
})
app.directive('childBDrtv', function() {
return {
restrict: 'E',
templateUrl: 'child-B-template.html',
//template: 'B<child-c-drtv></child-c-drtv>',
controller: function ($scope) {
console.log('childB Controller');
},
link: function() {
console.log('childB Link');
}
};
})
app.directive('childCDrtv', function() {
return {
restrict: 'E',
templateUrl: 'child-C-template.html',
//template: 'C',
controller: function ($scope) {
console.log('childC Controller');
},
link: function() {
console.log('childC Link');
}
};
});
孩子-A-template.html:
A<child-b-drtv></child-b-drtv>
孩子-B-template.html:
B<child-c-drtv></child-c-drtv>
孩子-C-template.html:
C
輸出:
childA Controller
childA Link
childB Controller
childB Link
childC Controller
childC Link
當您使用 '模板' 來代替 'templateUrl',你會得到不同的輸出。 app.js:
var app = angular.module('app', []);
app.directive('childADrtv', function() {
return {
restrict: 'E',
//templateUrl: 'child-A-template.html',
template: 'A<child-b-drtv></child-b-drtv>',
controller: function ($scope) {
console.log('childA Controller');
},
link: function() {
console.log('childA Link');
}
};
})
app.directive('childBDrtv', function() {
return {
restrict: 'E',
//templateUrl: 'child-B-template.html',
template: 'B<child-c-drtv></child-c-drtv>',
controller: function ($scope) {
console.log('childB Controller');
},
link: function() {
console.log('childB Link');
}
};
})
app.directive('childCDrtv', function() {
return {
restrict: 'E',
//templateUrl: 'child-C-template.html',
template: 'C',
controller: function ($scope) {
console.log('childC Controller');
},
link: function() {
console.log('childC Link');
}
};
});
輸出:
childA Controller
childB Controller
childC Controller
childC Link
childB Link
childA Link
'A child-b-drtv>'這就是你在'child-A- template.html'? –
Scorpion
您是否嘗試過幾次運行該程序?你確定它不是一個線程類型的問題嗎? –