Setting dynamic controller for directives in AngularJS

Working Demo in JSFiddle

Source : Checkout my answer in Stack OverFlow

HTML Markup

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

My AngularJS code look like,


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

Advertisements

One thought on “Setting dynamic controller for directives in AngularJS

  1. Fco Javier Fraguio says:

    Hi Raja,

    Thanks for your explanation! I´m trying to do this, but with a little twist: instead of hardcoding the controller-name in the html, I´m trying to use a variable from the scope to do it. Something like:

    But this is not working. I tried with {{controller-name=scope.controllerName}}, but I still don´t get any results. Do you know how can I do this?

    Thanks for your help!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s