0

I have an application with some controllers that have the same functions as: InitMenu, GetData, Search, Paging, ..

How can I build a generic controller with the main functions: InitMenu, GetData, Search, Paging, .. without having to write in each specific controller?

1 Answer 1

1

share all the common logic inside a service and inject it inside your controllers.

.service('CommonData, function(){
   this.getData = function(){
   }
   this.InitMenu= function(){
   }
   this.search= function(){
   } 
})

otherwise you can make a parent controller and all the child controllers will prototype inherit from the parent scope.

.controller('ParentCtrl', function($scope){
  $scope.myObj = {};
  $scope.parentMethod = function(){
    return myObj;
  }
})

.controller('ChildCtrl', function($scope){
 var stuff = $scope.parentMethod(); 
//you can access the parent method in the child template as well
})

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
      {{parentMethod()}}
      //if you use controllAs syntax change it to {{parentCtrlName.parentMethod()}}
    </div>
</div>

if you use controllerAs syntax you can access the parent $scope by specifyng the controller name as a scope field in the child controller. e.g $scope.parentCtrlName.parentMethod() and parentCtrlname.parentMethod() in the child template.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Karim, but my opinion is build a Controller that can be inherited by other controllers (it look like inheritance in .NET). Any way to make this?
yes you can make a parent controller , and all the children controllers will prototype inherit all the methods from the parent, i'll fix my answer :)
you're welcome, if the answer helped you please mark it as correct. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.