分离文件中的角度控制器不起作用

时间:2017-01-18 20:33:59

标签: angularjs

为什么控制器不能在分离的文件中工作?

申请结构:

See app structure here

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"
    }
}]);

3 个答案:

答案 0 :(得分:1)

编辑:根据@Claies的评论,我更新了答案以供将来参考。

  • 您必须更改 store.html 中的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>
  • 您还需要在 userController.js 中声明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)

应该在控制器之前首先在html中引用app.js。

而不是:

<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>