我认为使用 Angularjs 加载外部模板就像下面这样简单,
<div ng-include='template/index.php'></div>
但它不会在浏览器上打印任何内容。我错过了什么?
HTML,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Angualr</title>
<meta charset="utf-8">
<script src="js/angular.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/maincontroller.js" type="text/javascript"></script>
</head>
<body>
<div ng-include='template/index.php'></div>
</body>
</html>
模板,
<div id='content' ng-app='MyTutorialApp' ng-controller='MainController'>
<input type='text' ng-model='searchText' />
<ul>
<li ng-repeat='person in people | filter:searchText' ng-show='person.live == true'>#{{person.id}} {{person.name}}</li>
</ul>
<input type='text' ng-model='newPerson' />
<button ng-click='addNew()'>Add</button>
</div>
js/app.js,
var app = angular.module('MyTutorialApp',[]);
js/maincontroller.js,
app.controller("MainController", function($scope){
$scope.people = [
{
id: 0,
name: 'Leon',
music: [
'Rock',
'Metal',
'Dubstep',
'Electro'
],
live: true
},
{
id: 1,
name: 'Chris',
music: [
'Indie',
'Drumstep',
'Dubstep',
'Electro'
],
live: true
}
];
$scope.newPerson = null;
$scope.addNew = function() {
if ($scope.newPerson != null && $scope.newPerson != "") {
$scope.people.push({
id: $scope.people.length,
name: $scope.newPerson,
live: true,
music: [
'Pop',
'RnB',
'Hip Hop'
]
});
}
}
});
编辑:
目录,
index.html
js/
...
...
template/
index.php
编辑 2:
index.html,
<div ng-app='MyTutorialApp'>
<div ng-include='template/index.php'></div>
</div>
模板/index.php,
<div id='content' ng-controller='MainController'>
<input type='text' ng-model='searchText' />
<ul>
<li ng-repeat='person in people | filter:searchText' ng-show='person.live == true'>#{{person.id}} {{person.name}}</li>
</ul>
<input type='text' ng-model='newPerson' />
<button ng-click='addNew()'>Add</button>
</div>
最佳答案
ng-include 查找 $scope 属性,因此您需要向其传递一个字符串,如下所示:ng-include="'/template/index.php'"
。
<div ng-include="'/template/index.php'"></div>
你传递给它的本质上是让它在你的 Controller 中寻找这个:$scope['/template/index.php'] = 'some string';
您还在模板本身中引导 angular - 那么如何将它包含在内呢? ng-app
需要在主页中,这样 ng-include
才能工作!
<some-element ng-app="myApp">
<!-- in here, angular things work (assuming you have created an app called "myApp" -->
<div ng-include="'/template/index.php'"></div>
</some-element>
只需将 some-element
替换为 html
、body
或您希望应用运行的任何元素即可。
关于javascript - Angularjs 外部模板 : the template cannot be loaded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775874/