Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: how to pass scope variables to a directive?

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?

like image 862
I159 Avatar asked Apr 26 '13 09:04

I159


People also ask

How I use scope in a directive AngularJS?

The directive scope uses prefixes to achieve that. Using prefixes helps establish a two-way or one-way binding between parent and directive scopes, and also make calls to parent scope methods. To access any data in the parent scope requires passing the data at two places – the directive scope and the directive tag.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

How does scope inheritance work in AngularJS?

Scope InheritanceIf we define nested controllers, then the child controller inherits the scope of its parent controller. We assign values to the models in shapeController. We override message in child controller named circleController.

Which directive is used to assign values to the variables in AngularJS?

ng-init directive It is used to declare and assign values to the variables for an AngularJS application.


2 Answers

    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> 
like image 81
Joe Hanink Avatar answered Sep 18 '22 23:09

Joe Hanink


Read Attributes/observing interpolated attributes section of the directive docs. During the link phase the attributes haven't been set.

There are several ways including using attrs.$observe or $timeout.

app.directive('createControl', function($timeout){
 return function(scope, element, attrs){
      attrs.$observe('createControl',function(){
        console.log(' type:',attrs.createControl);
         element.text('Directive text, type is: '+attrs.createControl);
      });
  }
}) ;

DEMO

like image 45
charlietfl Avatar answered Sep 22 '22 23:09

charlietfl