JSON padding in AngularJS with ng-options

EDIT: My code really works, I was just an idiot with an unrelated problem. Thanks for your input.

So, I have an array of JSON objects formatted as follows:

[{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"},....]

I want to populate the AngularJS select box using them, with text fields as display text and id fields as values ​​or any other model-related. I looked around, but could not let my life determine what I needed to do.

Now I have this for my choice, as a result of which nothing is displayed:

<select name="field" ng-model="npe.formData.field" ng-options="field.id as field.text for field in fields">

Executing ng-parameters in this way leads to the display of things, but, obviously, will lead to binding the wrong value to the model:

ng-options="field as field.text for field in fields"

I saw people talking about using "(key, value)", but I can’t plunge into how it works.

+4
source share
2 answers

You will need (key, value) if you repeat the map, which is not so - in your example, you iterate through an array of objects. Usage (key, value) will be:

$scope.map={item1:'a',item2:'b'};
...
<li ng-repeat="(id,text) in map">{{id}}) {{text}}</li>

which will display "item1" etc.

Why did you mention the snippet below doesn't work?

ng-options="field.id as field.text for field in fields"

To issue this script - http://jsfiddle.net/7eqsc/2/ , it works like a charm and updates the model with the correct identifier.

<div ng-app="myApp">
<div ng-controller="myCtrl">

    <div ng-repeat="(id,text) in notes">{{text}}</div>
    <select ng-model="model.id" ng-options="note.id as note.text for note in notes" ></select>

    Selected id:{{model.id}}

</div>

+8
source

Fiddle, , . , , ng-model - , .

function TodoCtrl($scope) {
    $scope.fields = [{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"}];
    $scope.choice = null;
}

HTML

<div ng-app>
  <div ng-controller="TodoCtrl">
      <h2>Chosen = {{ choice }}</h2>
      <select ng-options="field.id as field.text for field in fields" ng-model="choice"></select>
  </div>
</div>

, , , , , ng-options ng-model , .

+3

Source: https://habr.com/ru/post/1544528/


All Articles