0

您有 2 个角度模块,其中一个模块具有您想在另一个模块中使用的服务:

var moduleA = angular.module ('moduleA', [])
                 .service('FirstService', function(){
                    var thing = {};
                    thing.data = ['1', 'alskdjf' , 0];
                    return thing;
                 });

var moduleB = angular.module('moduleB', []);

问题是 - 您如何在模块 B 中使用“FirstService”?

这失败了:

moduleB.controller('MBC', ['$scope', 'moduleA', function($scope, moduleA){}])

这些也失败了:

moduleB.controller('MBC', ['$scope', function($scope){
  var a = angular.injector().get('FirstService');
  var b = angular.injector().invoke('FirstService');
  var c = moduleA.service('FirstService');
  var d = moduleA.FirstService;

}])
4

3 回答 3

2
var moduleB = angular.module('moduleB', ['moduleA]);

这会将 moduleA 注入到 moduleB 中,然后您可以使用 moduleA 服务。

于 2015-04-13T04:50:06.777 回答
0

这是使用角度服务的简单示例。

mainApp.service('CalcService', function(MathService){
    this.square = function(a) {
        return MathService.multiply(a,a);
    }
});
mainApp.controller('CalcController', function($scope, CalcService) {
    $scope.square = function() {
       $scope.result = CalcService.square($scope.number);
    }
});
于 2015-04-13T05:02:23.253 回答
0

我在 Plunkr 中写了一个有效的答案。长话短说,您将第二个模块作为依赖项添加到第一个模块中。

从那里您可以注入附加到第二个模块的任何服务。

您根本不需要使用 .injector() 函数。(这也不是推荐的方式)。

转到此链接:http ://plnkr.co/edit/7Q6dvtpvFJforeJhT​​LCR?p=info

var app = angular.module('plunker', ['separateModule']);

app.controller('MainCtrl', function($scope, TestService) {
  $scope.title = 'Plunker Example for Stack Overflow';
  $scope.message = TestService.sayHi();
});

//Second module
var anotherModule = angular.module('separateModule', []);

//Let's declare of Service in the Second module
anotherModule.service('TestService', function() {
    this.message = 'Hello Stack Overflow';
    
    this.sayHi = function() {
      return this.message;
    };
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <h1>{{ title }}</h1>
    <p>
      {{ message }}
    </p>
  </body>

</html>

于 2016-05-12T18:57:52.157 回答