简体   繁体   English

AngularJS实现将所有输入作为可重用指令实现的最佳方法

[英]AngularJS best way to implement check all inputs as reusable Directive

I'm looking for the best way to implement a "check-all" input for multiple rows of input. 我正在寻找实现多行输入的“全部检查”输入的最佳方法。

In this case, since there are several types of list views, each one has it's own Directive and Controller. 在这种情况下,由于存在多种类型的列表视图,因此每种视图都有自己的指令和控制器。

I was thinking to implement the check-all control as an Attribute Directive, inside the parent Directive's template, something like: 我正在考虑将所有检查控件实现为父指令模板内的属性指令,例如:

<input check-all="'nameOfParentDirective'">

The idea is to pass along the name of the parent Directive as the value of the custom attribute, so this instance of the Check All Directive knows which parent scope to use, to thus check, or uncheck all of the rows in the respective table. 这个想法是将父指令的名称作为自定义属性的值传递,因此“检查所有指令”的此实例知道要使用哪个父作用域,从而检查或取消选中相应表中的所有行。

Here's where I got hung up, I wasn't sure how to dynamically set a require value. 这是我挂断电话的地方,我不确定如何动态设置需求值。 Setting it statically is easy: 静态设置很容易:

require: '^parentDirective',

But that won't work here. 但这在这里不起作用。

Perhaps I'm over-complicating things, I'm guessing there is an easier way to do this. 也许我使事情变得过于复杂,我猜想有一种更简单的方法可以做到这一点。

The end result is to bubble up the check/uncheck change event on the input to the parent Directive, so all of it's checkboxes can be either checked or unchecked accordingly... 最终结果是使父指令输入上的check / uncheck更改事件冒泡,因此可以相应地选中或取消选中所有复选框。

Cheers! 干杯!

I'd suggest taking another approach. 我建议采取另一种方法。 Instead of attempting to make this some sort of DOM manipulation challenge just update a model that stores the information about what's selected and use that to drive the view. 无需尝试进行某种DOM操作挑战,只需更新一个模型即可存储有关所选内容的信息,然后使用该模型来驱动视图。 So long as the collection of items has some shared property like "selected" then it doesn't matter what other properties the objects have so this can apply across any number of lists. 只要项目集合具有某些共享属性(如“选定”),则对象具有的其他属性并不重要,因此它可以应用于任意数量的列表。 Will include a sample here soon. 即将在此处提供样本。

 angular.module('TestApp', []) .factory('UtilFactory', function(){ var utilFact = {}; utilFact.selectAll = function(array){ for(var i=0; i<array.length; i++){ array[i].selected = true; } } return utilFact; }) .controller('SomeCtrl', function($scope, UtilFactory){ var randData = []; for(var i=0; i<100; i++){ randData.push({ id:i, data:Math.random() }); } $scope.someData = randData; $scope.UtilFactory = UtilFactory; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div ng-app="TestApp" ng-controller="SomeCtrl"> <button ng-click="UtilFactory.selectAll(someData)">Select All</button> <div ng-repeat="item in someData"> <label> <input type="checkbox" ng-model="item.selected"/> {{item.data}} </label> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM