作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
这是一个处理复选框不确定状态的指令:
.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/
我是一名优秀的程序员,十分优秀!