Reputation: 3189
If I'm using an isolated scope I can pass a variable over an attribute.
ie
<my-directive baz='foo.bar'>
Then, on the directive's Javascript
.directive('myDirective', function() {
return {
scope: {
'baz': '='
}
}
});
Is there any way to do something similar with an inherited scope? The link function just passes strings.
Right now I'm parsing the variable myself and matching it to scope.$parent. It seems like there should be a helper function or and easier way to do it.
Upvotes: 9
Views: 4752
Reputation: 364677
Use $eval
or $parse
:
<my-directive baz='foo.bar'>
.directive('myDirective', function($parse) {
return {
scope: true,
link: function(scope, element, attrs) {
console.log(scope.$eval(attrs.baz));
var model = $parse(attrs.baz);
console.log(model(scope));
// if you want to modify the value, use the model, not $eval:
model.assign(scope, "new value");
}
}
});
Upvotes: 14
Reputation: 169
with this code:
link: function(scope, elem, attrs) {}
you can use
attrs
element to get all atributes assign to this directive.
then you can simple assign attrs to any scope and use it in your e.x templae.
scope.someValue = attrs.attrName;
To sum up:
Directive:
link: function(scope, elem, attrs) {
scope.someValue = attrs.attrName;
}
Directive template:
<div> {{someValue}} <div>
Directive call
<my-directive attrName="foo"> </my-directive>
Upvotes: 3
Reputation: 3124
If you don't declare the scope object in the directive, there will be no isolated scope setup and you will get access to the scope that is passed in from where the div is declared in the DOM.
Something like this:
.directive('myDirective', function() {
return {
function(scope, element, attrs){
//scope here = the inherited scope from the DOM
}
}
So if you have your directive declared in the DIV tag, you don't need to actually send in the value as an attribute - you can just pull it out of the scope.
Upvotes: 0