[英]AngularJS set default value of an array of radio buttons by a nested id property?
参见JSFiddle 。
在AngularJS 1.2中,我试图找出是否有可能通过使用嵌套数据ID(字符串)而不是数组索引(整数)来引用数组中的对象?
这是我的数据:
$scope.sizes = [
{"dataId":"sm","label":"Small","price":8},
{"dataId":"med","label":"Medium","price":10},
{"dataId":"lg","label":"Large","price":11}
];
$scope.colors = [
{"dataId":"red","label":"Brick Red","price":41},
{"dataId":"blue","label":"Royal Blue","price":32},
{"dataId":"green","label":"Forest Green","price":35}
];
我想用选定的配置文件预填充模型:
var coolShoe = {
label:"Cool Shoe",
size:"lg",
color:"red"
}
我知道如何使用数组索引设置值:
$scope.myShoe.size = $scope.sizes[2];
$scope.myShoe.color = $scope.colors[0];
但是我想做这样的事情(不起作用):
$scope.myShoe.size = $scope.sizes.indexOf(coolShoe.size);
$scope.myShoe.color = $scope.colors.indexOf(coolShoe.color);
有可能吗? 我的数据结构是否错误? 我是否完全忽略了显而易见的事情? 提前致谢! 亚伦
代码使用indexOf()
在对象数组中搜索字符串,但找不到它(更不用说indexOf()
返回索引,而不是项目)。
您可以编写一个函数来自己搜索数组。 另一种方法是利用内置的角度过滤器通过dataId
搜索每个数组。
controllers.controller('myController', function($scope, $filter){
// ...
var coolShoe = {
label:"Cool Shoe",
size:"lg",
color:"red"
};
$scope.myShoe.size = $filter('filter')($scope.sizes, { 'dataId': coolShoe.size })[0];
$scope.myShoe.color = $filter('filter')($scope.colors, { 'dataId': coolShoe.color })[0];
});
尽管我不确定这是不是一个好的设计,但是可以使用过滤器来实现。 检出完整的JS Bin 。 这将是您的html:
<html ng-app="App">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"> </script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="MainCtrl">
<!-- can loop true with ng-repeat but just showing first item below -->
<p>Size: {{myShoe.size[0].label}}</p>
<p>Color: {{myShoe.color[0].label}}</p>
</div>
<script src="app.js"></script>
</body>
</html>
和您的javascript“ app.js”:
angular.module("App", [])
.controller("MainCtrl", function($scope, $filter) {
$scope.sizes = [
{"dataId":"sm","label":"Small","price":8},
{"dataId":"med","label":"Medium","price":10},
{"dataId":"lg","label":"Large","price":11}
];
$scope.colors = [
{"dataId":"red","label":"Brick Red","price":41},
{"dataId":"blue","label":"Royal Blue","price":32},
{"dataId":"green","label":"Forest Green","price":35}
];
$scope.coolShoe = {
label:"Cool Shoe",
size:"lg",
color:"red"
};
$scope.myShoe = {};
$scope.myShoe.size = $filter('filter')($scope.sizes, $scope.coolShoe.size);
$scope.myShoe.color = $filter('filter')($scope.colors, $scope.coolShoe.color);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.