Bind ng-options in the ng model on boot (e.g. bi-directional binding)

Situation:

I have the following choice:

<select ng-model="model" ng-options="o as o.name for o in options track by o.code">
    <option value="">- Default -</option>
</select>

My tags optionsare as follows:

$scope.options = [{id: 1, code: 'foo', name: 'Foo!'}, {id: 2, code: 'bar', name: 'Bar!'}];

What I want to do:

I want to have my choice with a pre-selected value. My limitation is that I only know the attribute of codemy object. With the sign, track byI can do it just like this:

$scope.model = {code: 'bar'};

And it works, the selected value of select is "Bar!"

Problem:

When I send this data to my server, I need to send an attribute of idmy object. Transmitted data {code: 'bar'}, but not {id: 2, code: 'bar', name: 'Bar!'}as I want.

This is normal behavior for me ... because I saved in my model {code: 'bar'}and I did not change the selected value.

Conclusion:

AngularJS options model, model ( track by)?

: , - $scope.model = $scope.options[2] ( ...), - ... ...: D

+4
2

OP. , - $scope.model = $scope.options [2] ( ...), - ... ...: D


3 3

1:

$scope.model = $scope.options.filter(function(item) {
  return item.code=== 'bar';
})[0];

2:

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

$scope.model  = $filter('getById')($scope.options, 2);

3

angular.forEach($scope.options, function(option) {
        $scope.model = option.name == "name";
        if($scope.model !=null){break}
    });
+2

ng-change <select>, , JSON.

HTML

<div ng-app='app' ng-controller='mainCtrl'>
    <select ng-model="model" ng-options="o as o.name for o in options track by o.code" 
    ng-change='getValue(this)'>
    <option value="">- Default -</option>
</select>
</div>

angular.module('app',['QuickList']).controller('mainCtrl', function($scope){
   $scope.options = [{id: 1, code: 'foo', name: 'Foo!'}, {id: 2, code: 'bar', name: 'Bar!'}];
   $scope.model = {code: 'bar'};
   $scope.getValue = function(item){
      console.log($scope.selectedOption = item.model);
   }
});

, <select>, JSON , .

JSFIDDLE

+1

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


All Articles