我正在尝试在选择标签上动态生成 ng-model 的名称,并使其在父范围内可访问(如表二所示),但显然让它们彼此独立工作。
所以我的问题是如何将 ng-model 设置为类似“$parent.ot1”对象数据数组?
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>
最佳答案
将 $scope.selected
初始化为 Controller 中的数组:
$scope.selected = [];
然后在 ng-model
指令中使用 $index
:
<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>
关于javascript - 如何使用动态值将 ng-model 设置为父范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49701442/