Tommy1209
Tommy1209

Reputation: 189

Angularjs: How to build a controller reuseable?

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?

Upvotes: 0

Views: 35

Answers (1)

Karim
Karim

Reputation: 8632

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.

Upvotes: 1

Related Questions