2014-10-20 60 views
5

我正在製作一個AngularJs模塊。事情是,這個模塊是假設與其他模塊(它就像一個插件)一起工作。所以我基本上會在稍後從另一個模塊導入這個模塊。但是,這個模塊中有一些服務,我想稍後從導入該模塊的模塊中進行重寫。我會怎麼做?簡單地定義另一個同名的服務呢?如果是這樣,我將如何獲得原始服務?最重要的AngularJs服務

+3

你檢查['$ provide.decorator'(https://docs.angularjs.org/api/auto /服務/ $#提供裝飾)? – Yoshi 2014-10-20 11:18:31

+0

啊!這會做。謝謝! – asdacap 2014-10-20 11:36:49

回答

3

覆蓋將根據模塊的實例化順序發生。 創建的最後一個模塊將優先於在其之前創建重複服務的模塊。

SO服務的鏈接關於命名空間:"Namespacing" services in AngularJS

Plunker:http://plnkr.co/edit/P488AkNtGYGUXmo9gIAT?p=preview

var dep1 = angular.module("dep1",[]); 
    var dep2 = angular.module("dep2",[]); 
    var app = angular.module("app",["dep2","dep1"]); 

    dep1.factory("helloSrvc",function(){ 
    return { 
     msg: "hello from dep1" 
    } 
    }); 

    dep2.factory("helloSrvc",function(){ 
    return { 
     msg: "hello from dep2" 
    } 
    }); 

    app.controller("myCtrl", function(helloSrvc,$scope){ 
    $scope.msg = helloSrvc.msg; 
    }); 

    angular.bootstrap(document,["app"]);