AngularJS Modules and External Controllers

后端 未结 2 2223
轻奢々
轻奢々 2021-01-15 05:26

I have a page containing multiple containers. Each container will have its own controller but point to one factory, which handles all the logic interacting with a web servic

2条回答
  •  無奈伤痛
    2021-01-15 05:59

    Here is a example of an Angular module setup I am using in an app that allows a separate external file for each module type. Note that the app must load before the external files. Tested on Angular 1.4.9.

    Index.html

    
    
    
    
    
    

    ng-app.js

    var app = angular.module('myApp', [
        'factories',
        'directives',
        'controllers'
    ]);
    

    ng-controllers.js

    //note: I am injecting the helloFac factory as an example
    var ctrl = angular.module('controllers', []);
    
    ctrl.controller('MyCtrl', ['$scope', 'helloFac', function($scope, helloFac) {
        console.log(helloFac.sayHello('Angular developer'));
    }]);
    

    ng-directives.js

    angular.module('directives',[])
        .directive('test', function () {
            return {
                //implementation
            }
        })
        .directive('test2', function () {
                return {
                    //implementation
                }
        });
    

    ng-factories.js

    var factories = angular.module("factories", []);
    
    factories.factory('helloFac', function() {
        return {
            sayHello: function(text){
                return 'Hello ' + text;
            }
        }
    });
    

提交回复
热议问题