AngularJS定制指令对一个复选框NG-不确定的属性 [英] AngularJS custom directive for a ng-indeterminate attribute on checkboxes

查看:682
本文介绍了AngularJS定制指令对一个复选框NG-不确定的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是处理复选框上的不确定状态指令:

Here is a directive that handles the indeterminate state on checkboxes:

.directive('ngIndeterminate', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            attributes.$observe('ngIndeterminate', function(value) {
                $(element).prop('indeterminate', value == "true");
            });
        }
    };
})

然后,例如与这些数据:

Then, for example with these data:

$scope.data = [
    {name: 'foo', displayed: 2, total: 4},
    {name: 'bar', displayed: 3, total: 3}
];

您将只需:

<ul ng-repeat="item in data">
    <li>
        <input type="checkbox" ng-indeterminate="{{item.displayed > 0 && item.displayed < item.total}}" ng-checked="item.displayed > 0" />
        {{item.name}} ({{item.displayed}}/{{item.total}})
    </li>
</ul>

有没有办法写的NG-不确定前pression没有双卷曲的符号,就像原生的NG-检查吗?

Is there any way to write the ng-indeterminate expression without the double-curly notation, just as the native ng-checked one?

ng-indeterminate="item.displayed > 0 && item.displayed < item.total"

我试过:

.directive('ngIndeterminate', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            attributes.$observe('ngIndeterminate', function(value) {
                $(element).prop('indeterminate', $compile(value)(scope));
            });
        }
    };
})

不过,我得到以下错误:

But I get the following error:

Looking up elements via selectors is not supported by jqLite!

这里是一个小提琴你可以玩。

推荐答案

首先,你不需要包装元素在jQuery的,如果你之前加载的jQuery的 角。所以,你就再不会需要使用 $(元素)您的指令内,而是可以使用元素直接作为角意志自动换行元素作为一个jQuery对象。

First off, you do not need to wrap element in jQuery if you load jQuery before angular. So you would then never need to use $(element) inside your directives and instead can use element directly as angular will automatically wrap element as a jQuery object.

有关你的榜样,你实际上并不甚至不需要jQuery的,所以下面提供的答案不依赖于jQuery的都没有。

For your example, you don't actually even need jQuery, so the answer provided below does not rely on jQuery at all.

至于你的问题,你可以 $观看你的属性值,角度自动返回编译后的属性值。所以下面的作品,你会期望:

As to your question, you can $watch your attribute values, angular automatically returns the compiled attribute value. So the following works as you would expect:

.directive('ngIndeterminate', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            scope.$watch(attributes['ngIndeterminate'], function (value) {
                element.prop('indeterminate', !!value);
            });
        }
    };
});

下面是一个工作的jsfiddle http://jsfiddle.net/d9rG7/5/

这篇关于AngularJS定制指令对一个复选框NG-不确定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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