AngularJS自定义指令,用于复选框上的ng-indeterminate属性

sp0*_*00m 10 javascript checkbox angularjs angularjs-directive

这是一个处理复选框上不确定状态的指令:

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

然后,例如使用这些数据:

$scope.data = [
    {name: 'foo', displayed: 2, total: 4},
    {name: 'bar', displayed: 3, total: 3}
];
Run Code Online (Sandbox Code Playgroud)

你只需要:

<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>
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有双卷曲符号的情况下编写ng-indeterminate表达式,就像本机ng-checked一样?

ng-indeterminate="item.displayed > 0 && item.displayed < item.total"
Run Code Online (Sandbox Code Playgroud)

我试过了:

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

但是我收到以下错误:

Looking up elements via selectors is not supported by jqLite!
Run Code Online (Sandbox Code Playgroud)

这是一个你可以玩的小提琴.

Bey*_*ers 10

首先,element如果 angular 之前加载jQuery ,则不需要包装jQuery .因此,您将永远不需要$(element)在指令中使用,而是可以element直接使用angular element作为jQuery对象自动换行.

对于您的示例,您实际上甚至不需要jQuery,因此下面提供的答案根本不依赖于jQuery.

至于你的问题,你可以通过$watch属性值自动返回已编译的属性值.因此,以下工作正如您所期望的那样:

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

这是一个有效的jsfiddle:http://jsfiddle.net/d9rG7/5/


ndp*_*dpu 5

使用scope.$evalelement.prop直接改变属性:

.directive('ngIndeterminate', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            attributes.$observe('ngIndeterminate', function(value) {
                element.prop('indeterminate', scope.$eval(value));
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

小提琴


通过使用,attributes.$observe您只能捕获包含插值(即 {{}} 的)的属性更改。您应该使用scope.$watch可以观察/观看“表情”的内容。所以,我认为@Beyers 的回答更正确。感谢注意到@Chi_Row