如何在角度指令中绑定布尔值? [英] How to bind boolean values in angular directives?

查看:93
本文介绍了如何在角度指令中绑定布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些布尔属性绑定/设置为指令.但是我真的不知道该怎么做以及如何实现以下行为.

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.

想象一下,我想为一个结构设置一个标志,假设一个列表是否可折叠.我有以下HTML代码:

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是双向绑定的,name只是一个属性

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

我希望通过传递双向绑定的值(true,false或其他值)在列表的$ scope中使用该collapsable属性

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>

我正在开发一些UI组件,我想提供多种与它们交互的方式.也许及时,有些人想通过将对象的属性传递给属性来了解该组件的状态(是否折叠).

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.

谢谢

推荐答案

您可以为布尔值配置自己的1-way数据绑定行为,如下所示:

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);
    });

}

在此处使用$ observe意味着您的监视"仅受属性更改的影响,并且如果您直接在指令内部更改$ scope.collapsable,则不会受到影响.

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.

这篇关于如何在角度指令中绑定布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆