在 angularJS 选择指令中设置所选项目 [英] Setting the selected item in angularJS select directive

查看:21
本文介绍了在 angularJS 选择指令中设置所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular 的 select 指令中设置所选项目时遇到问题.我不知道这是 angular 的设计者的错误还是有意识的设计.不过,它确实让 select 指令变得不那么有用了.

I have a problem with setting the selected item in angular's select directive. I don't know if this is a bug or a conscious design from the designers of angular. It sure makes the select directive a lot less useful though.

说明:

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

My app communicates with a REST API to receive an entity from the database. The API dictates that relations of the object are sent with an ID property only so that you can retrieve them in subsequent requests if needed.

示例:

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

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

where city is another entity that can be retrieved through a different REST endpoint using the city id and looks like so:

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

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

I need to create a form to edit the customer entity with a dropdown menu with all possible cities so that the user can select the appopriate city from the list. The list must initially display the customer's city as retrieved from the JSON object.

表格是这样的:

 <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> 

控制器看起来像这样:

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 指令必须将加载的城市设置为列表中的选定项目.

What should happen: once the full details of the City object are loaded the select directive must set the city that was loaded as the selected item in the list.

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

What happens: the list displays an empty item and there's no way to initialize the selected item if the selected item from objects outside the array of items.

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

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

Is there a solutions for this? Can the selected item be set programmatically in a generic way so that the AJAX calls and select logic be refactored into a reusable AJAX based select widget ?

推荐答案

就是这么简单

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

然后在你的控制器里面:

Then inside you 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:在处理对象数组时使用.此表达式的结果将用于标识数组中的对象.trackexpr 很可能会引用 value 变量(例如 value.propertyName).

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 属性来确定应该将哪个元素设置为活动元素.

The rest is just assigning a value to the $scope.item variable and angular will figure out which element should be set as active by checking the item's name property.

这篇关于在 angularJS 选择指令中设置所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆