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?
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.
The $ in AngularJs is a built-in object.It contains application data and methods.
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.
ng-init directive It is used to declare and assign values to the variables for an AngularJS application.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With