How to set the dynamic controller for directives?

Now it is possible with AngularJS. In directive you just add two new property called
controller , name property and also isolate scope is exactly needed here.

Important to note in directive

scope:{}, //isolate scope
controller : "@", // @ symbol
name:"controllerName", // controller names property points to controller.

Working Demo for Setting Dynamic controller for Directives

HTML Markup :

<communicator controller-name="PhoneCtrl" ></communicator>
<communicator controller-name="LandlineCtrl" ></communicator>

Angular Controller and Directive :

var app = angular.module('myApp',[]).
directive('communicator', function(){
return {
    restrict : 'E',
    scope:{},
    controller : "@",
    name:"controllerName", 
    template:"<input type="text" ng-model="message"/><input type="button" value="Send Message" ng-click='sendMsg()'><br/>"          
  }   
}).
controller("PhoneCtrl",function($scope){
 $scope.sendMsg = function(){
     alert( $scope.message + " : sending message via Phone Ctrl");
    }
}).
controller("LandlineCtrl",function($scope){
    $scope.sendMsg = function(){
        alert( $scope.message + " : sending message via Land Line Ctrl ");
    }
})

Your case you can try this below code snippets.

Working Demo

HTML Markup :

<div add-icons controller-name="IconsOneCtrl">
</div>
<div add-icons controller-name="IconsTwoCtrl">
</div>

Angular Code :

angular.module('myApp',[]).

directive('addIcons', function(){
return {
    restrict : 'A',
    scope:{},
    controller : "@",
    name:"controllerName",    
    template:'<input type="button" value="(+) plus" ng-click="add()">'
  }
}).
controller("IconsOneCtrl",function($scope){
     $scope.add = function(){
        alert("IconsOne add ");
      }
}).
controller("IconsTwoCtrl",function($scope){
     $scope.add = function(){
        alert("IconsTwo add ");
      }
});

Leave a Comment