2016-06-25 46 views
1
  1. 我正在使用角度「控制器as」語法,只需提供'Constructor '註冊控制器時。
  2. 我也想實現與「原型」語法

這裏的繼承是我的代碼角度「控制器爲」+「控制器構造函數」+原型oop +顯式注入服務基類內部(使用[...])

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <script src="https://code.angularjs.org/1.4.3/angular.min.js"></script> 
 
    <script type="text/javascript"> 
 
     var app = angular.module("test",[]); 
 

 
     //---------------------------- 
 
     function BaseController() { 
 
      this.name = 'Base'; 
 
     } 
 

 
     BaseController.prototype.baseMethod = function() { 
 
      conso.log(this.name); 
 
     } 
 

 
     app.controller('controllerBase', BaseController) 
 
     //---------------------------- 
 
     function ControllerA() { 
 
      BaseController.call(this); 
 
      this.name = 'A'; 
 
     } 
 

 
     ControllerA.prototype = Object.create(BaseController.prototype); 
 
     ControllerA.prototype.constructor = ControllerA; 
 

 
     ControllerA.prototype.a = function() 
 
     { 
 
      console.log('A specific'); 
 
     } 
 

 
     app.controller('controllerA', ControllerA); 
 
     //---------------------------- 
 
     function ControllerB() { 
 
      BaseController.call(this, 'B'); 
 
      this.name = 'B'; 
 
     } 
 

 
     ControllerB.prototype = Object.create(BaseController.prototype); 
 
     ControllerB.prototype.constructor = ControllerB; 
 

 
     ControllerB.prototype.b = function(){ 
 
      console.log('B specific'); 
 
     } 
 

 
     app.controller('controllerB', ControllerB); 
 
    </script> 
 
</head> 
 
<body ng-app="test"> 
 
    <div ng-controller="controllerA as vm"> 
 
     <h1>{{vm.name}}</h1> 
 
     <input type="button" ng-click="a()" value="A: click me" /> 
 
    </div> 
 

 
    <div ng-controller="controllerB as vm"> 
 
     <h1>{{vm.name}}</h1> 
 
     <input type="button" ng-click="b()" value="B: click me"/> 
 
    </div> 
 
</body> 
 
</html>

這工作正常,到目前爲止,但我的問題是:

如果在方法'baseMethod'內BaseController,我想使用其他服務,如$ http,$ q或servicexyz,...我如何注入它們? (和使用顯式注入[...],沒有隱含的)

BaseController.prototype.baseMethod = function() { 
 
      need to use $http, $q, ... here 
 
     }

回答

1

您需要設置構造控制器的公共財產:然後

function ControllerA($http, $q) { 
    BaseController.call(this); 
    this.name = 'A'; 
    this.$http = $http; 
    this.$q = $q; 
} 

app.controller('controllerA', ['$http', '$q', ControllerA]); 

你會像這樣的訪問服務

BaseController.prototype.baseMethod = function() { 
    this.$http.get('...') 
    // this.$q.resolve() etc. 
} 
+0

絕對是你的好吧,我想過這個,但是,比方說,我有幾百個控制器從基地繼承,然後我們必須複製和粘貼...很多,每一次我們改變基礎構造函數的簽名,然後我們必須在數百個地方進行更換 – khoailang

+0

那麼從理論上來看,您會如何看待它?不知道什麼*「那麼我們必須複製並粘貼」*表示,複製粘貼什麼? – dfsq

+0

有你複製這個。$ http = $ http;這個。$ q = $ q;並粘貼到每個派生控制器的構造函數?每個ControllerA ... ControllerX仍然需要這些? – khoailang