Lev Lev - 1 year ago 154
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
, it gets converted to a string.

How can I pass a boolean value to

Answer Source

Use scope.$eval:

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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download