2015-05-01 34 views
4

這是我在嘗試使控制器更加可重用時發現的。AngularJS:使用調用的控制器繼承(或應用)

app.factory('BaseController', function(myService) { 
    return function(variable) { 
    this.variable = variable; 
    this.method = function() { 
     myService.doSomething(variable); 
    }; 
    }; 
}) 

.controller("ChildController1", function($scope, BaseController) { 
    BaseController.call($scope, "variable1"); 
}) 

.controller("ChildController2", function($scope, BaseController) { 
    BaseController.call($scope, "variable2"); 
}); 

現在我可以做我的HTML這樣的事情(例如NG-控制器= 「ChildController1」 中):NG-點擊= 「方法()」

只簡單的工作。但我不知道它是如何工作的(它是什麼樣的模式?),這樣做會是一個好習慣嗎?

回答

1

你的解決方案的工作或多或少是這樣的:

app.factory('mixinBaseController', function(myService) { 
    return function (scope, variable) { 
    angular.extend(scope, { 
     variable: variable; 
     method: function() { 
     myService.doSomething(variable); 
     } 
    }); 
    }; 
}) 

.controller("ChildController1", function($scope, mixinBaseController) { 
    mixinBaseController($scope, "variable1"); 
}) 

.controller("ChildController2", function($scope, mixinBaseController) { 
    mixinBaseController($scope, "variable2"); 
}); 

你能看到什麼?通過您的.call($scope, ...)只是將上下文(this)設置爲真實的$scope,這樣BaseController只是將屬性和功能擴展到您的範圍。

這只是爲了演示您的代碼如何工作。

爲了實現如繼承一個更多的JavaScript,請參閱:

你應該也有一個看看"controllerAs" syntax在AngularJS 1.2中引入。我強烈建議使用controllerAs。這也應該有助於爲您的控制器實現繼承。