我想开发一个主页面的网站,该网站可以路由到其他几个页面。所有页面都有自己的app.js
文件及其自己的.controller
,以便于代码管理。
pages.html
<html ng-app="myPageApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.js"></script>
<script src="js/mypages.js"></script>
</head>
<body>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><i class="fa fa-home"></i> Home</a></li>
<li><a href="#users"><i class="fa fa-comment"></i> Users</a></li>
</ul>
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view></div>
</body>
</html>
mypages.js
var myPageApp = angular.module("myPageApp",['ngRoute']);
myPageApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/users.html',
});
});
users.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="../js/myusers.js"></script>
</head>
<body>
<div ng-app="myUsersApp">
<div ng-controller="UsersCtrl">
<ul class="unstyled">
<li ng-repeat="user in UsersCtrl.users">
<span >{{user}}</span>
</li>
</ul>
<input type="text" ng-model="user" placeholder="Name please">
User {{user}}
</div>
</div>
</body>
</html>
myusers.js
var myUsersApp = angular.module("myUsersApp",['']);
myUsersApp.controller('UsersCtrl',[ '$scope', function($scope){
$scope.users = ['john','marry'];
$scope.add = function() {
$scope.users.push($scope.user);
$scope.user = "";
}
}]);
我永远无法让myusers.js
工作。当我Inspect element
时,似乎根本没有调用myusers.js
。有什么想法吗?
答案 0 :(得分:0)
经过多次测试和更多reading,我发现它是如何工作的。
<强> pages.html 强>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.js"></script>
<script src="js/mypages.js"></script>
<script src="js/usersctrl.js"></script>...
在着陆页上添加所有controllers
js
个文件。链接的顺序很重要。
<强> mypages.js 强>
var myApp = angular.module("myApp",['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/users.html',
controller : 'UsersCtrl'//<--add this
});
});
将控制器与特定页面链接。上面的示例pages/users.html
- &gt; UsersCtrl
。
<强> usersctrl.js 强>
var app= angular.module('myApp');
myApp.controller('UsersCtrl',[ '$scope', function($scope){
console.log("UsersCtrl");
$scope.clickMe = function() {
console.log("i m clicked!");
}
}]);
照常创建函数并将其填充到controller``js
。
信息页/ users.html 强>
<body>
<div>
<button ng-click="clickMe()">Click me!</button>
</div>
请注意,在users.html
中,无需再添加ng-app
和ng-controller
。这也很重要。