扩展 AngularJS 控制器的推荐方法是什么? [英] What's the recommended way to extend AngularJS controllers?
问题描述
我有三个非常相似的控制器.我想要一个控制器,由这三个扩展并共享其功能.
也许你不扩展控制器,但可以扩展控制器或使单个控制器混合多个控制器.
module.controller('CtrlImplAdvanced', ['$scope', '$controller', function ($scope, $controller) {//初始化超类并扩展它.angular.extend(this, $controller('CtrlImpl', {$scope: $scope}));... 用于创建 mixin 的附加扩展.}]);
当父控制器被创建时,其中包含的逻辑也会被执行.有关更多信息,请参阅 $controller() ,但只需要传递 $scope
值.所有其他值将正常注入.
@mwarren,Angular 依赖注入会自动神奇地解决您的问题.您只需要注入 $scope,尽管您可以根据需要覆盖其他注入的值.以下面的例子:
(function(angular) {var module = angular.module('stackoverflow.example',[]);module.controller('simpleController', function($scope, $document) {this.getOrigin = function() {返回 $document[0].location.origin;};});module.controller('complexController', function($scope, $controller) {angular.extend(this, $controller('simpleController', {$scope: $scope}));});})(角度);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script><div ng-app="stackoverflow.example"><div ng-controller="complexController as C"><span><b>来自控制器的来源:</b>{{C.getOrigin()}}</span>
虽然$document在'complexController'创建时没有传递给'simpleController',但是$document是为我们注入的.
I have three controllers that are quite similar. I want to have a controller which these three extend and share its functions.
Perhaps you don't extend a controller but it is possible to extend a controller or make a single controller a mixin of multiple controllers.
module.controller('CtrlImplAdvanced', ['$scope', '$controller', function ($scope, $controller) {
// Initialize the super class and extend it.
angular.extend(this, $controller('CtrlImpl', {$scope: $scope}));
… Additional extensions to create a mixin.
}]);
When the parent controller is created the logic contained within it is also executed.
See $controller() for for more information about but only the $scope
value needs to be passed. All other values will be injected normally.
@mwarren, your concern is taken care of auto-magically by Angular dependency injection. All you need is to inject $scope, although you could override the other injected values if desired. Take the following example:
(function(angular) {
var module = angular.module('stackoverflow.example',[]);
module.controller('simpleController', function($scope, $document) {
this.getOrigin = function() {
return $document[0].location.origin;
};
});
module.controller('complexController', function($scope, $controller) {
angular.extend(this, $controller('simpleController', {$scope: $scope}));
});
})(angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script>
<div ng-app="stackoverflow.example">
<div ng-controller="complexController as C">
<span><b>Origin from Controller:</b> {{C.getOrigin()}}</span>
</div>
</div>
Although $document is not passed into 'simpleController' when it is created by 'complexController' $document is injected for us.
这篇关于扩展 AngularJS 控制器的推荐方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!