Updating a model using ng-options and ng-selected

I am trying to update a model from the drop down menu using ng-options and select an already selected value using ng-selected. Here's a simplified example (and fiddle ).

HTML

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter.id" ng-options="q.id as q.val for q in Quarters">
      <option ng-selected="Quarter.val===q.val"></option>
    </select>
    <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
    <br/>
    <p>{{answer}}</p>
  </div>
</div>

Angular

function QuarterController($scope) {
    $scope.Quarters = [{val: 'Q1', id: 1}, {val: 'Q2', id:2}, {val:'Q3', id:3}, {val:'Q4', id:4}];
    $scope.Quarter = {val: 'Q2', id: 2, extraField: 'Hello'};

    $scope.submit = function() {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id + $scope.Quarter.extraField;
    };
}

So what happens here, the “val” from $ scope.Quarters is the dropdown, with the selected option identifier stored in $ scope.Quarter.id. "submit" displays the id and val of $ scope.Quarter. $ scope.Quarter.id updates to send, but not $ scope.Quarter.val. Does anyone know how to do this?

EDIT

$ scope.Quarter.extraField has been added to better illustrate the problem I'm trying to solve. I need id and val to update, but I want extraField to stay the same.

+4
1

, , .

:        

Todo

  <div ng-controller="QuarterController">
    <select name="quarter" ng-model="Quarter" ng-options="q.val for q in Quarters">
        <option value="">{{Quarter.val}}</option>
    </select>
      <input type="button" name="Submit" value="Submit" ng-click="submit()"/>
      <br/>
      <p>{{answer}}</p>

  </div>
</div>

JS:

function QuarterController($scope) {
    $scope.Quarters = [{
        val: 'Q1',
        id: 1
    }, {
        val: 'Q2',
        id: 2
    }, {
        val: 'Q3',
        id: 3
    }, {
        val: 'Q4',
        id: 4
    }];
    $scope.Quarter = {
        val: 'Q2',
        id: 2
    };

    $scope.submit = function () {
        $scope.answer = "Val: " + $scope.Quarter.val + ", Id: " + $scope.Quarter.id;
    };
}
+2

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


All Articles