AngularJS: Inject controller inside another controller from the same module

前端 未结 4 1011
耶瑟儿~
耶瑟儿~ 2021-02-12 16:12

Is possible to inject a controller into another controller that is part of the same module?

example:

4条回答
  •  一个人的身影
    2021-02-12 16:22

    If the a controllerTwo needs to call the same function as controllerOne, you may want to create a service to handle it. Angular Services - they are accessible throughout your program through dependency injection.

    var app = angular.module('myAppModule', [])
    .controller('controllerOne', ['$scope', 'Hello', function($scope, Hello){
       console.log(Hello.helloWorld() + ' controller one');
    }])
    .controller('controllerTwo', ['$scope', 'Hello', function($scope, Hello){
       console.log(Hello.helloWorld() + ' controller two');
    }])
    .factory('Hello', [function() {
       var data = {
          'helloWorld': function() {
              return 'Hello World';
           }
       }
    
       return data;
    }]);
    

    Hope this helps!

提交回复
热议问题