使用角度ng-select,寻找最佳实践/建议,将选择下拉列表与根据范围内对象的属性选择的所选选项相关联。
以下是plunker:http://plnkr.co/edit/bMj7678djgPoJbiTRceG?p=preview
服务/控制器JS。
selectDemo = angular.module('selectDemo',[]);
selectDemo.factory("cat", ["$http", "$log", function($http, $log){
return {
query: function(runAfter){
$log.debug("Getting cats from service");
return $http.get('getCats.json');
}
}
}]);
selectDemo.controller('SelectDemoCtrl', ["$scope", "$log", "cat", function($scope, $log, Cat){
$scope.animal = {type: "Mammal", cat: {"id": 2, "name": "Simon", "breed": "Persian"}};
Cat.query().then(function(data){
cats = data.data;
$scope.cats = cats;
});
}]);
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="selectDemo" ng-controller="SelectDemoCtrl">
<h1>AngularJS Select Dropdown</h1>
<div id="data"></div>
<form role="form">
<select data-ng-model="animal.cat" data-ng-options="cat.name for cat in cats">
<option value="">Select a cat</option>
</select>
</form>
<p>You selected: {{ animal.cat }}</p>
</body>
</html>
JSON响应对象:
[{"id": 1, "name": "Garfield", "breed": "Tabby"},
{"id": 2, "name": "Simon", "breed": "Persian"},
{"id": 3, "name": "Twix", "breed": "Mixed"}]
答案 0 :(得分:1)
这是一个更新的插件:
http://plnkr.co/edit/KTJt9602eD5Pgr1y7c9w?p=preview
这里的问题是ng-options
中的所选对象需要引用到ng-model
引用的对象,因此需要在{{1}}中找到对象阵列。