angular.js - Problem with multiple controllers in angular
过去多啦不再A梦
过去多啦不再A梦 2017-05-15 16:51:58
0
3
559

See this way of writing

//app.js
angular.module('app',['app.controllers']);

//FirstController.js
angular.module('app.controllers').controller('firstCtrl',function($scope){...})

//SecondController.js
angular.module('app.controllers').controller('SecondCtrl',function($scope){...})    

But when I write the missing report like this, firstCtrl and SecondCtrl are not the same method. I just started learning angular, please help

过去多啦不再A梦
过去多啦不再A梦

reply all(3)
洪涛

It is recommended to write like this

angular
    //app.js
    .module('app',[])//这个'[]'用来创建依赖

    //FirstController.js
angular
    .module('app')//这个后面没有'[]',表面继续用之前创建的[]依赖
    .controller('firstCtrl',['$scope',function($scope){//这里用[]来规范写法,防止压缩文件后看不懂形参
        ...
    }])

    //SecondController.js
angular
    .module('app')//同上
    .controller('SecondCtrl',['$scope',function($scope){
        ...
    }])
滿天的星座
angular.module('app.controllers').controller('firstCtrl',function($scope){...})

The premise of this statement is that you have a view whose ng-app is app.controllers.
The first parameter of the module function is the value of ng-app.
The controller function is to define a controller under the module.

给我你的怀抱

angular.module('app.controllers',[]).
Note here that when a module is first defined, you need to fill in the dependencies. If there are no dependencies, you need to fill in the empty array. If you reference the same module elsewhere later, there is no need to fill in the dependencies.

When you define the two controllers here, the dependencies are not filled in. They need to be changed to the following.

angular.module('app.controllers',[]).controller('firstCtrl',function($scope){...})
angular.module('app.controllers').controller('SecondCtrl' ,function($scope){...})

Note: Different dependencies will generate different instances, so please note that after the definition is completed, you must not fill in the dependencies again the next time you reference it, otherwise the previous related definition will be invalid. This is a bug that is difficult to troubleshoot.

For questions about angular style, it is recommended to refer to the master https://github.com/johnpapa/angular-styleguide

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template