为什么控制器不能在分离的文件中工作?
申请结构:
store.html :
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>
<div ng-controller="userController">
<h1>{{user.firstname}}</h1>
</div>
<script src="/static/app/user/userController.js"></script>
<script src="/static/app/app.js"></script>
</body>
</html>
app.js :
var app = angular.module("myApp",[]);
app.controller("myContoller",["$scope",function ($scope) {
}]);
userController.js
app.controller("userController",["$scope",function ($scope) {
$scope.hello= "john doe";
$scope.user = {
id:1,
firstname:"Wojciech"
}
}]);
答案 0 :(得分:1)
编辑:根据@Claies的评论,我更新了答案以供将来参考。
script
代码的顺序,如下所示:<强> store.html 强>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>
<div ng-controller="userController">
<h1>{{user.firstname}}</h1>
</div>
<script src="/static/app/app.js"></script>
<script src="/static/app/user/userController.js"></script>
</body>
</html>
app
,就像在 app.js 中一样。<强> userController.js 强>
var app = angular.module("myApp"); //locate the module first
app.controller("userController",["$scope",function ($scope) {
$scope.hello= "john doe";
$scope.user = {
id:1,
firstname:"Wojciech"
}
}]);
答案 1 :(得分:0)
在userController.js之前输入app.js
如果您想在单独的文件中定义控制器,您可以这样做。您只需要获取应用参考。
userController.js
/*
angular.module call without "[]" returns the app object
rather than creating a new app.
*/
var app = angular.module("app");
app.controller("ControllerName", ["$scope", function($scope){
// controller code here.
}]
答案 2 :(得分:0)
而不是:
<script src="/static/app/user/userController.js"></script>
<script src="/static/app/app.js"></script>
这样做:
<script src="/static/app/app.js"></script>
<script src="/static/app/user/userController.js"></script>