在这个plnkr中,我尝试以编程方式构建一个文本值数组并在角度js视图中显示它们:
http://plnkr.co/edit/kOUKq9IuxE38QKAUSFJ1?p=preview
但是没有显示这些值。我认为问题在于这个代码:
var vp = [];
vp.push("Blue: true");
这是构建数组的正确方法吗? Shoud'这在json上是否正确序列化,以便angularjs可以正确显示值?
如果我改变:
var vp = [];
vp.push("Blue: true");
到
var vp = {Blue: true, Orange: true};
它正常工作。
plnkr来源:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Multiple Checkboxes</title>
<style>
label {display: block;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
</head>
<body>
<div ng:controller="MainCtrl">
<label ng-repeat="(color,enabled) in colors">
<input type="checkbox" ng-model="colors[color]"> {{color}}
</label>
<p>colors: {{colors}}</p>
<script>
var app = angular.module('plunker', []);
var vp = [];
vp.push("Blue: true");
app.controller('MainCtrl', function($scope){
$scope.colors = vp;
});
</script>
</body>
</html>
接受答案的来源:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Multiple Checkboxes</title>
<style>
label {display: block;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
</head>
<body>
<div ng:controller="MainCtrl">
<label ng-repeat="color in colors">
<input type="checkbox" ng-model="color.enabled"> {{color.name}}
</label>
<p>colors: {{colors}}</p>
<script>
var app = angular.module('plunker', []);
var vp = [];
vp.push({name:'Blue', enabled:true});
vp.push({name:'Black', enabled:true});
app.controller('MainCtrl', function($scope){
$scope.colors = vp;
});
</script>
</body>
</html>
答案 0 :(得分:1)
您只需在此处向数组添加字符串:
var vp = [];
vp.push("Blue: true");
通常,您绑定到符合{ property: x, property:b }
语法的对象文字:
var vp = [];
vp.push( { Blue: true, NestedObject: { Color: 'Red'} });
答案 1 :(得分:0)
这是另一种选择,将对象添加到索引数组而不是布尔值到关联数组。
Javascript:
var vp = [];
vp.push({name:'Blue', enabled:true});
HTML:
<label ng-repeat="color in colors">
<input type="checkbox" ng-model="color.enabled"> {{color.name}}
</label>