Angular - DI依赖注入不同模块之间的连接和来自另一个模块的service \ directive

时间:2015-05-16 08:30:10

标签: angularjs

如果我需要使用其他模块的工厂,我是否需要先将模块的DI添加到当前模块中,然后将工厂的DI添加到当前工厂?或者我可以只添加工厂本身(没有模块)?

所以,如果真的超过它的真实,Di在模块中的唯一用途就是用于......或者我错过了其他的东西?

2 个答案:

答案 0 :(得分:0)

var myApp = angular.module('myApp', []);
myApp.service('myService', function() {
  // do some stuff
});
myApp.controller('otherCtrl', function($scope, myService) {
  // do some stuff
});

myApp 模块注入 otherApp 模块并使用服务 myService

var otherApp = angular.module('otherApp', ['myApp']);
otherApp.controller('myCtrl', function($scope, myService) {
    $scope.myService = myService; 
});

答案 1 :(得分:0)

声明具有dependecies的模块。

var baseApp = angular.module("ERMSApp", ['ngSanitize', 'ngRoute', 'ngTable']);

var baseApp1 = angular.module("ERMSApp1", ['ERMSApp', 'ngSanitize', 'ngRoute', 'ngTable']);

宣布服务。

baseApp.factory("getEmployeesService", function ($http) {
var promise;
var getEmployeesService = {
    getEmployees: function () {
        if (!promise) {
            var promise = $http.get("/Timesheet/GetEmployees").then(function (result) {
                return result;
            });
        }
        return promise;
    }
}
return getEmployeesService;

});

在另一个模块中使用服务

baseApp1.controller("leaveOnBehalfCtrl", function ($scope, $http, $filter, $sce, ngTableParams, $compile, getEmployeesService) {
getEmployeesService.getEmployees().then(function (data) {
    $scope.employees = data.data;
})

});