Using $attrs To Evaluate Attribute With Curly Braces In It
To get the proper value in the controller you can use either $parse
or $interpolate
depending upon what you have passed through your directive's attributes. If you passed just the name of the property then you can use $parse otherwise if you have an interpolated string you need to use $interpolate which gets executed in the given context.
In your case you need to use $interpolate like below
In HTML
<bodyng-app='app'ng-controller='mCTRL'><h1>Hello Plunker!</h1><file-uploadname="myUploader"upload-url="{{url}}/files"auto-upload="true"
></file-upload></body>
Your Directive should look like below
app.directive('fileUpload',function(){
return{
restrict:'EA',
controller:function($scope,$attrs,$interpolate){
var myUrl=$interpolate($attrs.uploadUrl)($scope)
},
link(scope,elem,attrs,ctrl){
}
}
})
Solution 2:
You can access your directive's attributes through it's link function shown below, you can use this to set the value from the attribute
main.directive('fileUpload', function () {
return {
...
link: function ($scope, elem, attr) {
$scope.uploadUrl = attr.upload-url; //note attr.upload-url might cause problems, not sure if you can have dashed attribute names
}
};
});
Solution 3:
If you put your logic in a link function instead of a controller, then the attrs.uploadUrl passed to the attrs argument of that link function will already be interpolated for you. That is how I would recommend solving your problem, although the solution proposed by Rishi will work as well.
app.directive('fileUpload', function() {
return {
restrict : 'EA',
link : function(scope, elem, attrs) {
var myUrl = attrs.uploadUrl;
}
};
});
The only reason I have ever found to use a directive controller rather than a link function is when I actually want to inject that controller into another directive via the require property for facilitating inter-directive communication.
Note however that if some parent directive defines scope properties you want interpolated in its own post-link function, they will not be defined yet in a descendant's post-link, as those run in reverse from leaf to root. If you run into that issue you should use the pre-link function to define such properties on the scope so that they are available where you want them.
Post a Comment for "Using $attrs To Evaluate Attribute With Curly Braces In It"