Extending Angular.js controller
When working in Angular applications you might need to create multiple controllers at first then you realise some of them perform similar tasks. By creating a base controller and extending its behaviour in other controllers you can minimise code.
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 mixing.
}]);
The logic within the parent controller is also executed when it is created. If the extended controller has a lot of arguments then these arguments needs to be typed in the extending controller method signature. This is taken care by Angular dependency injection. You need to inject $scope.
(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>
Comments
0 comments
Please Sign in or Create an account to Post Comments