How to bind boolean values in angular directives?

46,265

Solution 1

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.

Solution 2

Create a scope on the directive that sets up bi-directional binding:

app.controller('ctrl', function($scope)
{
    $scope.list = {
        name: 'Test',
        collapsed: true,
        items: [1, 2, 3]
    };
});

app.directive('list', function()
{
    return {
        restrict: 'E',
        scope: {
            collapsed: '=',
            name: '=',
            items: '='
        },
        template:
            '<div>' +
                '{{name}} collapsed: {{collapsed}}' +
                '<div ng-show="!collapsed">' +
                    '<div ng-repeat="item in items">Item {{item}}</div>' +
                '</div>' +
                '<br><input type="button" ng-click="collapsed = !collapsed" value="Inside Toggle">' +
            '</div>'
    };
});

Then pass the options in as attributes:

<list items="list.items" name="list.name" collapsed="list.collapsed"></list>

http://jsfiddle.net/aaGhd/3/

Solution 3

You can't pass strings true or false as the attribute value, and also support passing a scope property such as list.collapsed as the attribute value for two-way binding. You have to pick one way or the other.

This is because you can only specify one way to interpret the attribute's value in your directive when using an isolate scope.

I suppose you could use = in your diretive, and also check in your linking function if attrs.collapsable is set to true or false: if so, then you know a boolean value was passed, and if not, use the two-way data binding. But this is hacky.

Solution 4

Since Angular 1.3 attrs.$observe seems to trigger also for undefined attributes, so if you want to account for an undefined attribute, you need to do something like:

link: function(scope, element, attrs) {
    attrs.$observe('collapsable', function() {
      scope.collapsable = scope.$eval(attrs.collapsable);
      if (scope.collapsable === undefined) {
        delete scope.collapsable;
      }
    });
  },

Solution 5

I know I'm like a year late on this, but you can actually do this by using the link function (https://docs.angularjs.org/guide/directive). The signature looks like this:

function link(scope, element, attrs) { ... } 

That attrs object will be filled out with the raw values passed in. So you could say if (attrs.collapsed == 'true') { ... } or some such.

Share:
46,265
Chris X
Author by

Chris X

Updated on March 06, 2020

Comments

  • Chris X
    Chris X over 4 years

    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

    • Chris X
      Chris X almost 11 years
      setting the attribute as two-way binded with '=' won't work when passing direct boolean values true or false because I can't set the scope's value to another one. e.g. $scope.collapsable = false;
    • Ajay Beniwal
      Ajay Beniwal almost 11 years
      will you collapsable attribute value change at run time or remain the same at the time of deslaration
    • Ajay Beniwal
      Ajay Beniwal almost 11 years
      if values is not going to change then just use attrs["collapsable"]
    • Chris X
      Chris X almost 11 years
      as I said, the value might change within the controller
  • Chris X
    Chris X almost 11 years
    Definitely, this works! But I'd like also to be able to set the collapsed attribute with a boolean value, with true or false
  • Charlie Martin
    Charlie Martin almost 10 years
    That's not going to work. All values inside an attribute are of type string. So if you were to set collapsed="false", then check if (attrs.collapsed), it would be true, because the string "false" is truthy
  • Brandon Prudent
    Brandon Prudent almost 10 years
    Indeed. I updated the example with a simple 'true' string test. I think it does address the intent of the question.
  • user1338062
    user1338062 over 9 years
    I find using $scope/$element/$attrs names here confusing, because link does not get injections, only positional arguments. So scope, element, attrs would be more appropriate.
  • Bloke
    Bloke almost 9 years
    Is there any difference between scope.$eval() and javascript's native eval() function?
  • cesaraviles
    cesaraviles almost 9 years
    @Bloke Here's a SO question you may find helpful. stackoverflow.com/questions/15671471/…