How to bind boolean values in angular directives?

Chris X picture Chris X · Aug 2, 2013 · Viewed 44.9k times · Source

I'd like to bind/set some boolean attributes to a directive. But I really don't know how to do this and to achieve the following behaviour.

Imagine that I want to set a flag to a structure, let's say that a list is collapsable or not. I have the following HTML code:

<list items="list.items" name="My list" collapsable="true"></list>

items are two-way binded, name is just an attribute

I'd like that collapsable attribute to be available in the list's $scope either by passing a value (true, false or whatever), either a two-way binding

<list items="list.items" name="{{list.name}}" collapsable="list.collapsed"></list>

I'm developing some UI components and I'd like to provide multiple way of interacting with them. Maybe, in time, some guys would like to know the state of that component, either is collapsed or not, by passing an object's property to the attribute.

Is there a way to achieve this? Please correct me if I missunderstood something or I'm wrong.

Thanks

Answer

bingles picture bingles · Jul 18, 2014

You can configure your own 1-way databinding behavior for booleans like this:

link: function(scope, element, attrs) {

    attrs.$observe('collapsable', function() {

        scope.collapsable = scope.$eval(attrs.collabsable);
    });

}

Using $observe here means that your "watch" is only affected by the attribute changing and won't be affected if you were to directly change the $scope.collapsable inside of your directive.