【问题标题】:Angular controller in separated files does not work单独文件中的角度控制器不起作用
【发布时间】:2017-06-03 09:26:42
【问题描述】:

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

应用结构:

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

【问题讨论】:

  • 如果您还没有解决问题,请查看我的答案(已更新)。现在应该可以工作了

标签: angularjs


【解决方案1】:

在 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】:

    编辑:根据@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"
            }
        }]);
    

    【讨论】:

    【解决方案3】:

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

    代替:

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

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2017-10-25
      • 2014-10-25
      • 1970-01-01
      相关资源
      最近更新 更多