Javascript angularJs-两种不同结构的不同模型是否可以同步或共享状态?
我有一个从数据库返回的列表中加载的复选框和值列表 控制器Javascript angularJs-两种不同结构的不同模型是否可以同步或共享状态?,javascript,angularjs,Javascript,Angularjs,我有一个从数据库返回的列表中加载的复选框和值列表 控制器 listA = ['item1','item2'...'itemn']; //Master list of items $scope.selectedItems = ["item1",... "item5"]; //selected items $scope.attributesModel = [ //new model based on selected items {"index":5,"att
listA = ['item1','item2'...'itemn']; //Master list of items
$scope.selectedItems = ["item1",... "item5"]; //selected items
$scope.attributesModel = [ //new model based on selected items
{"index":5,"attribute":"item1"},
{"index":10, "attribute":"item2"},
{"index":13, "attribute":"item3"},
{"index":21, "attribute":"item4"},
{"index":24, "attribute":"item5"}
];
视图第1部分
<td>
<div class="checkbox checkbox-notext">
<input checklist-model="selectedItems" checklist-value="key" type="checkbox" id="{{key}}" ng-disabled="exceededLimit && !checked" />
</div>
</td>
<td>
<label for="{{key}}">{{key}}{{$index}}</label>
</td>
{{key}}{{$index}
视图第2部分
<div ng-repeat="(index, row) in attributesModel" >
<div class="margin10">
<div>Index<input ng-model="row.index" value="row.index" type="number" class="indexInputs"></input>{{row.attribute}}</div>
</div>
</div>
索引{row.attribute}
现在我想同步$scope.selectedItems和$scope.AttributeModel。取消选中复选框时,selectedItems和AttributeModel模型都会删除该项,反之亦然。因此,每次有人选中新复选框时,都会显示一个带有空文本字段的AttributeModel,以键入索引值
catch对于添加到attributesModel的每个新选择的项目,索引键最初为空。创建新项目后,用户必须输入新索引
我尝试过使用watch,但遇到的问题是,当选择新项目时,我无法访问该项目本身。我只能访问列表,而不知道新项目是X还是删除的项目是Y,以便推送/删除正确的项目
所以这可能是我错过的手表解决方案
如果我能澄清任何问题,请告诉我。我不确定问题出在哪里,但您可以在复选框上使用
ngChange
:
<input type="checkbox" ... ng-change="..." />
$watch侦听器由3个参数(newValue、oldValue、scope)调用,也许你可以比较oldValue和newValue来确定需要推送/拼接哪个项目?@JonathanGawrych我如何才能查看列表中的单个项目?如果我查看列表,newValue和oldValue只是整个列表,不知道删除了哪个项目(除非我迭代列表).有什么方法可以查看列表中的单个项目吗?我使用的是这里的检查表指令@EKet:我以为这是yur指令。看看我更新的答案。
<input type="checkbox" ... ng-change="changed(key)" />
/* In the controller: */
...
$scope.changed = function (key) {
if ($scope.selectedItems.indexOf(key) === -1) {
// The checkbox for `key` was unchecked...
} else {
// The checkbox for `key` was checked...
}
};