简体   繁体   English

在选择中使用ng-options或ng-repeat?

[英]use ng-options or ng-repeat in select?

I want use select in angularjs. 我想在angularjs中使用select I have a json that every element have 2 part: name and value . 我有一个json,每个元素都有2部分: namevalue I want show name in dropdown and when user select one of theme, value is copy to ng-model . 我想在下拉列表中显示name ,当用户选择主题之一时, value将复制到ng-model

$scope.list = [{name:"element1",value:10},{name:"element2",value:20},{name:"element3",value:30}];

For this I have 2 way to use select: 为此,我有2种使用方式:

  1. ng-options : ng-options

I use ng-options like below: 我使用ng-options如下所示:

<select ng-model="model.test" ng-options="element.name for element in list"></select>

It's work correctly, but when I select each of element, I want just value of element is copy to ng-model, but a json is copy to ng-model, like below: 这是正常工作,但是当我选择每个元素的,我只想value元素是副本NG-模型,而是一个JSON是副本NG-模型,如下图所示:

$scope.model.test = {name:"element1",value:1}

I can resolve this problem in angular controller, but I want find a better way that resolve this problem. 我可以在角度控制器中解决此问题,但我想找到解决此问题的更好方法。

For resolove this problem, I use second way: 为了解决这个问题,我使用第二种方法:

2.use ng-repeat in options : 2.在options ng-repeat

    <select ng-model="model.test">
      <option ng-repeat="element in list" value="{{element.value}}">{{element.name}}</option>
    </select>

In second way, just value is copy to ng-model, but as a string type: 在第二种方法中,将value复制到ng-model,但是作为字符串类型:

$scope.model.test = "10";

I use below code, but all of them return a string value to model. 我使用以下代码,但是所有代码都将字符串值返回给模型。

<option ng-repeat="element in list" value={{element.value}}>{{element.name}}</option>
<option ng-repeat="element in list" value="{{element.value}}|number:0">{{element.name}}</option>
<option ng-repeat="element in list" value={{element.value}}|number:0>{{element.name}}</option>

How can fix this problem? 如何解决这个问题?

Have you tried this : 您是否尝试过:

 <select ng-model="model.test" ng-options="element.value element.name for element in list"></select>

btw, if you may have hundreds of records into your list, you should create your own directive, where you would manipulate your DOM with a simple javascript for loop 顺便说一句,如果您的列表中可能有数百条记录,则应创建自己的指令,在该指令中,您可以使用简单的JavaScript for循环来操作DOM

ng-repeat will be slow to be rendered, ng-options adds every record into $watch. ng-repeat的渲染速度很慢,ng-options将每条记录添加到$ watch中。

you can resolve it with ng-options as well 您也可以使用ng-options解决它

      ng-options="element.value as element.name for element in list"

please read this blog to understand more about ng-options. 请阅读此博客以了解有关ng-options的更多信息。

Also another advantage of ng-options is, it binds the object as opposed to json string in case you want to attach the selected object to ng-model. ng-options的另一个优点是,如果要将所选对象附加到ng-model,它将绑定对象而不是json字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM