How to bind boolean values in angular directives?

余生长醉 提交于 2019-12-03 23:29:31

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.

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/

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.

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.

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;
      }
    });
  },
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!