[英]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.