Angularjs: how to pass scope variables to a directive?

I159 picture I159 · Apr 26, 2013 · Viewed 50.1k times · Source

I am trying to use directive to create and append several tags to a <div> as shown below:

module.directive('createControl', function(){
  return function(scope, element, attrs){    
    console.log(attrs.createControl); // undefined     
  }                                          
});                                         


<div class="control-group" ng-repeat="(k, v) in selectedControls">
  <div create-control="{{ v.type }}"></div>
</div>

In attrs I have this construction:

$$element: b.fn.b.init[1]
$$observers: Object
$attr: Object
createControl: "date"
style: "margin-right: 15px"
__proto__: Object

But when I try to use attrs.createControl I get undefined and I do not understand why. Actual question: how to pass scope variable to a directive?

Answer

Joe Hanink picture Joe Hanink · Apr 26, 2013
    app.directive('createControl', function() {
      return {
        scope: {
          createControl:'='
        },
        link: function(scope, element, attrs){    
           element.text(scope.createControl);    
        }      
      }
    })  

  <div class="control-group" ng-repeat="v in [{type:'green'}, {type:'brown'}]">
    <div create-control="v.type"></div>
   </div>