我正在使用 AngularJS 动态表单。根据我的用户 ID 值,我使用 ng-repeat 生成了具有相同模型名称的多个表单字段。我正在使用选择框来加载位置。默认情况下,根据我的要求,我需要将第一个选项值加载到该选择框中。我正在使用 ng-init 加载第一个选项数据,但它不起作用。在控制器内部,我试图获取像 $scope.user.location 这样的选择框模型值,但它显示错误。任何人都可以请您为这个问题发送一些 js fiddle 解决方案。
HTML
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<select ng-model="user.location" ng-options="v for v in locations" ng-init='user.location=location[0]' name="select2" required>
</select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</div>
JS
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
//i am trying this method also
/*$scope.user.location.push($scope.locations[0]);
$scope.user.location = $scope.user.location.slice();
console.log($scope.user.location) its doesnt work. */
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});