gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:00 26 4
gpt4 key购买 nike

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

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

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

$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-indeterminate 表达式,就像原生的 ng-checked 表达式一样?

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

但是我得到以下错误:

Looking up elements via selectors is not supported by jqLite!

Here is a fiddle你可以玩。

最佳答案

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

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

关于你的问题,你可以$watch你的属性值,angular会自动返回编译后的属性值。因此,以下工作如您所料:

.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/

关于javascript - 用于复选框上 ng-indeterminate 属性的 AngularJS 自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22143417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com