gpt4 book ai didi

angularjs - 在 angularJS select 指令中设置所选项目

转载 作者:行者123 更新时间:2023-12-02 22:12:50 25 4
gpt4 key购买 nike

我在 Angular 的 select 指令中设置所选项目时遇到问题。我不知道这是一个bug还是Angular的设计者有意识的设计。但它确实使 select 指令的用处大大降低。

描述:

我的应用程序与 REST API 通信以从数据库接收实体。 API 规定对象的关系仅与 ID 属性一起发送,以便您可以在需要时在后续请求中检索它们。

示例:

{ id : 1, customerName : "some name", city : {id : 12}} 

其中 city 是另一个实体,可以使用城市 ID 通过不同的 REST 端点进行检索,如下所示:

{ id: 12, name : "New York"}

我需要创建一个表单来编辑客户实体,其中包含包含所有可能城市的下拉菜单,以便用户可以从列表中选择适当的城市。该列表最初必须显示从 JSON 对象检索到的客户所在城市。

表单如下所示:

 <form>
<input type="text" ng-model="customer.name"/>
<select ng-model="customer.city" ng-options="i as i.name for i in cities"></select>
</form>

Controller 看起来像这样:

app.controller('MainCtrl', function ($scope, $http) {
$http.get(serviceurl + 'admin/rest/customer/' + id + "/", {
params: {"accept": "json"},
withCredentials: true
}).then(function (response) {
$scope.customer = response.data.item;
});
$http.get(serviceurl + 'admin/rest/city/', {
params: {"accept": "json"},
withCredentials: true
}).then(function (response) {
$scope.cities = response.data.items;
// THIS LINE LOADS THE ACTUAL DATA FROM JSON
$scope.customer.city = $scope.findCity($scope.customer.city);
});
$scope.findCity = function (city) {
for (var i = 0; i < $scope.cities.length; i++) {
if ($scope.cities[i].id == city.id) {
return $scope.cities[i];
}
}
}
});

应该发生什么:一旦加载了 City 对象的完整详细信息,select 指令必须将加载的城市设置为列表中的选定项目。

会发生什么:该列表显示一个空项目,如果所选项目来自项目数组之外的对象,则无法初始化所选项目。

此处问题的演示:http://plnkr.co/edit/NavukDb34mjjnQOP4HE9?p=preview

有解决办法吗?是否可以以通用方式以编程方式设置所选项目,以便将 AJAX 调用和选择逻辑重构为可重用的基于 AJAX 的选择小部件?

最佳答案

就这么简单

<select
ng-model="item"
ng-options="item.name for item in items track by item.name">

然后在你的 Controller 内部:

// all items
$scope.items = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
// set the active one
$scope.item = {name: 'b'};
// or just
$scope.item = $scope.items[1]

查看 http://docs.angularjs.org/api/ng.directive:select从那里:

trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).

剩下的只是为 $scope.item 变量分配一个值,Angular 将通过检查项目的 name 属性来确定应将哪个元素设置为事件元素。

关于angularjs - 在 angularJS select 指令中设置所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com