Lev Lev - 1 month ago 19
AngularJS Question

Directive attribute forces boolean to string

I want to pass a value to my directive without isolating its scope.

My directive has a link function to grab the value of the attribute:

link: function(scope, element, attrs, ctrl) {

scope.myAttributeValue = attrs.myAttribute;

}


I would like to do

<directive my-attribute="{{true}}"></directive>


When I pass a boolean value to
my-attribute
, it gets converted to a string.

How can I pass a boolean value to
my-attribute
?

Answer

Use scope.$eval:

app.directive("myDirective", function(){
    return function linkFn(scope,elem,attrs) {
        var x = scope.$eval(attrs.myDirective);
        console.log(x);
        console.log(typeof x);
    }
});

HTML

<div ng-app="myApp">
    <p my-directive="true"></p>
</div>

The $eval() method evaluates a string as an Angular Expression and will retain the type.

Avoid using interpolation (double curly brackets {{true}}) as that converts the Angular Expression to a string.

For more information, see AngularJS $rootScope.Scope API Reference --$eval

The DEMO on JSFiddle