简体   繁体   中英

How to set ng-model to parent scope with a dynamic value

I am trying to dynamically generate a name for the ng-model on the select tags, and have it accessible in the parent scope like on table two, but obviously have them work independent of each other.

So my question is how do I set the ng-model to something like "$parent.ot1" data array of objects?

  var overtimeapp = angular.module('overtime', []); overtimeapp.controller('ctrlOvertime', function ($scope, $http) { $scope.overtimes = [{"otid" : "ot1"}, {"otid" : "ot2"}]; $scope.overtimetypes = ['d', 'n', 'r', 's', 'h']; }); 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> </head> <body> <div ng-app="overtime" ng-controller="ctrlOvertime"> table one <table class="table table-bordered"> <tbody> <tr ng-repeat="o in overtimes"> <td> <select class="w3-select" ng-model="o.otid" ng-options="x for x in overtimetypes"></select> </td> </tr> </tbody> </table> table two <table class="table table-bordered"> <tbody> <tr ng-repeat="o in overtimes"> <td> <select class="w3-select" ng-model="$parent.selected" ng-options="x for x in overtimetypes"></select> </td> </tr> </tbody> </table> </div> </body> </html> 

Initialize $scope.selected as an array in the controller:

$scope.selected = [];

Then use $index in the ng-model directive:

  <table class="table table-bordered">
    <tbody>
      <tr ng-repeat="o in overtimes">
        <td>
          <select class="w3-select"
                  ̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶$̶p̶a̶r̶e̶n̶t̶.̶s̶e̶l̶e̶c̶t̶e̶d̶"̶
                  ng-model="selected[$index]"
                  ng-options="x for x in overtimetypes">
          </select>
        </td>
      </tr>
    </tbody>
  </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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