我正在尝试将一个模型绑定到一个内部有一个重复的指令上的一个重复。在外面,我看起来像这样
<div flex="25" ng-model="filterList">
<div ng-repeat="filter in searchResults.filters" class="builder-result-filters" ng-model="filterlist.filter.name"></div>
</div>因此,我尝试绑定一个名为filterList的模型中的所有内容,然后第一个重复将通过它的名称绑定第一个重复。然后在指令中,它看起来是这样的:
<div>
<ul>{{filter.name}}
<li ng-repeat="value in filter.values">
<input type="checkbox" ng-model="filterlist.filter.value">{{value}}
</li>
</ul>
Filters : {{filterlist}}
</div>(尝试打印模型以查看其是否正常工作)
因此,传入的初始数据如下所示:
"filters": [{
"name": "state",
"values": ["Saved", "Committed", "Published"]
},{
"name": "discipline"
"values": ["Marketing"]
}]基本上,我想做一个模型,像这样输出(基于这些重复)
{
{state : {{"saved" : true, "Committed" : false , "Published" : true}},
{discipline : {{"marketing" : true}}
}或者类似的东西。如果我可以将里面的项放在一个数组中,并在检查输入时显示出来,那么我就会加分,如下所示:
{
{state : ["saved", "Published" ]},
{discipline : []}
}因此,未选中的项目将不会显示。这至少是最终目标。现在,我只是想把这些都绑定到一个模型上。
所以我可以部分地实现我想要的--我尝试了这样的东西:
<div>
<ul >{{filter.name}}
<li ng-repeat="value in filter.values track by $index">
<input type="checkbox" ng-model="testingModel[filter.name][value]">{{value}}
</li>
</ul>
Filters : {{testingModel}}
</div>这就是结果:
{"discipline":{"Marketing":true},"state":{"Saved":true,"Committed":true}}我想知道是否有一种快速而肮脏的方法将复选框转换为数组,该数组可以根据值是真还是假来添加或删除值-就像这样:
{"discipline":["Marketing"],"state":["Saved"]}假设我在那里取消选中了提交的。
发布于 2015-04-15 08:47:14
ng-model可以从数组中读取数据,但不能使用push()或splice()。
因此,编写您自己的指令来将数组绑定到复选框:
.directive('awArray', function() {
return {
restrict: 'A',
scope: {
array: '=awArray',
value: '@'
},
link: function(scope, element) {
element.on('click', function(event) {
var index = scope.array.indexOf(scope.value);
scope.$apply(function() {
if (event.target.checked) {
if (index < 0) scope.array.push(scope.value);
} else {
if (index >= 0) scope.array.splice(index, 1);
}
});
});
}
};
});模板:
<li ng-repeat="item in ctrl.items"><input type="checkbox" array="ctrl.selection" value="{{item.name}}">{{item.name}}</li>https://stackoverflow.com/questions/29569494
复制相似问题