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

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

问题描述

我想为指令绑定/设置一些布尔属性.但我真的不知道如何做到这一点并实现以下行为.

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

我希望 collapsable 属性在列表的 $scope 中可用,方法是传递一个值(真、假或其他),要么是双向绑定

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.

谢谢

推荐答案

您可以像这样为布尔值配置自己的单向数据绑定行为:

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天全站免登陆