我正在尝试使用角度js构建选择项目组件。但它没有选择正确的默认选择值。
我正在将选择项值初始化为{"brandSetCode":1,"bannerColor":null,"fontColor":null};
但它总是选择最后一个元素。如何解决这个问题?
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-sanitize.js"></script>
</head>
<body ng-app="sanitizeExample">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope, $sce) {
$scope.initSelectItem ={"brandSetCode":null,"bannerColor":null,"fontColor":null};
$scope.mySelectableItems =[{
"label": "All",
"value": {
"brandSetCode": null,
"bannerColor": null,
"fontColor": null
}
}, {
"label": "SPIRITS",
"value": {
"brandSetCode": 1,
"bannerColor": null,
"fontColor": null
}
},
{
"label": "WINES",
"value": {
"brandSetCode": 3,
"bannerColor": null,
"fontColor": null
}
}
];
}]);
</script>
<div ng-controller="ExampleController">
<select name="brand"
data-ng-model="initSelectItem"
data-ng-options="brand.value as brand.label for brand in mySelectableItems track by $index">
</select>
</div>
</body>
</html>
答案 0 :(得分:0)
使用ng-init()
并初始化默认选项。
<select ng-init="initSelectItemDefault()" ng-model="initSelectItem" ng-options="brand.label for brand in mySelectableItems">
</select>
在控制器中
$scope.initSelectItemDefault = function(){
$scope.initSelectItem = $scope.mySelectableItems.filter(e => e.label == "All")[0];
}
答案 1 :(得分:0)
您需要删除track by
或手动比较它们,因为track by会在模型中添加名为$$ hash的字段。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-sanitize.js"></script>
</head>
<body ng-app="sanitizeExample">
<script>
angular.module('sanitizeExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope, $sce) {
$scope.initSelectItem = {};
$scope.mySelectableItems =[{
"label": "All",
"value": {
"brandSetCode": -1,
"bannerColor": -1,
"fontColor": -1
}
}, {
"label": "SPIRITS",
"value": {
"brandSetCode": 1,
"bannerColor": null,
"fontColor": null
}
}
];
}]);
</script>
<div ng-controller="ExampleController">
<select name="brand" ng-init="initSelectItem = mySelectableItems[0].value"
data-ng-model="initSelectItem"
data-ng-options="brand.value as brand.label for brand in mySelectableItems">
</select>
</div>
</body>
</html>
&#13;