我有一个JSON对象,我用ng-repeat重复,键是字符串,值是一个数组.我将每个值列为复选框.我想创建第二个对象,其中包含仅检查的复选框的列表.我想用键和值保留对象的结构.
我不确定如何正确地将它绑定到模型,以便保留结构.
http://jsfiddle.net/NDFc2/3/
这是我的HTML
Dynamic data binding in AngularJS
Inputs
{{parent}} :
Outputs
- {{key}} : {{output[key]}}
和我的JS
function Controller($scope) { $scope.output = {}; $scope.inputs = {'category': ['one','two','three'], 'color':['blue','green']}; }
有一些简单的方法可以做到这一点吗?我觉得我错过了一些小事,这一切都很好用.
我的示例在推荐的语法中使用了您的角度逻辑(非全局).我纠正了你的标记也有几个问题.
在此示例中,ng-model="x"
是一个占位符,我不使用,但ng-model
必须存在或抛出错误.我ng-change
用来处理复选框和之间的链接$scope.outputs
.
现场演示(点击).
标记:
<div ng-app="myApp" ng-controller="myCtrl"> <h3 >Dynamic data binding AngularJS</h3> <h4>Inputs</h4> <ul> <li ng-repeat="(typeKey, typeVal) in inputs"> <span>{{typeKey}} : </span> <ul> <li ng-repeat="value in typeVal"> <label>{{value}} <input type="checkbox" ng-model="x" ng-change="setOutput(typeKey, $index, value)" > </label> </li> </ul> </li> </ul> <h4>Outputs</h4> <ul ng-repeat="(key,value) in inputs"> <li>{{key}} : {{outputs[key]}}</li> </ul> </div>
JavaScript的:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.outputs = {}; $scope.inputs = { 'category': ['one','two','three'], 'color':['blue','green'] }; $scope.setOutput = function(typeKey, $index, value) { $scope.outputs[typeKey] = $scope.outputs[typeKey] || []; $scope.outputs[typeKey][$index] = value; }; });
现场演示(点击).
首先,我用ng-init
动态添加,从第一级属性inputs
来outputs
.然后,你只需要设置你ng-model
和ng-checked
属性在正确的位置outputs
.
标记:
<div ng-app="myApp" ng-controller="myCtrl"> <h3 >Dynamic data binding AngularJS</h3> <h4>Inputs</h4> <ul> <li ng-repeat="(typeKey, typeVal) in inputs" ng-init="outputs[typeKey] = outputs[typeKey] || {}"> <span>{{typeKey}} : </span> <ul> <li ng-repeat="value in typeVal"> <label>{{value}} <input type="checkbox" ng-model="outputs[typeKey][value]" ng-checked="outputs[typeKey][value]" value="outputs[typeKey][value]" > </label> </li> </ul> </li> </ul> <h4>Outputs</h4> <ul ng-repeat="(key,value) in inputs"> <li>{{key}} : {{outputs[key]}}</li> </ul> </div>
JavaScript的:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.outputs = {}; $scope.inputs = { 'category': ['one','two','three'], 'color':['blue','green'] }; });