Return to site
· Angular JS,Web Applications,Development,Controllers,Extend
broken image

 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. 

    // 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.

 

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}));