[英]How to set array objects int json object with AngularJS?
我要從多重選擇控件中加載數組對象,然后我要加載名為“名稱”的模型對象及其名稱和年齡值,然后我要從select中加載數組並在模型對象中加載...。但是從select中選擇ng-model控制無效:/
<input type="text" class="form-control" ng-model="model.name" placeholder="Put your name..." />
<input type="text" class="form-control" ng-model="model.age" placeholder="Put your age..." />
<!--Select pets for model person-->
<select ng-repeat="pets in arrayFromApi" class="selectpicker" multiple>
<option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
</select>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };
$scope.arrayFromApi = function() {
......
this function get id names
}
});
</script>
您可能需要使用ng-options。 您可以嘗試使用ng-repeat,但是它應該僅在選項標簽上。
避免在下拉列表上使用ng-repeat,因為它會引起一些性能問題。 而是使用ng-options。
為了給模特提供名字,年齡和寵物。 檢查mixData功能。
<input type="text" class="form-control" ng-model="model.name" placeholder="Put your name..." />
<input type="text" class="form-control" ng-model="model.age" placeholder="Put your age..." />
<!--Avoid ng-repeat in dropdowns-->
<!--Select pets for model person-->
<select ng-change="mixData()" class="selectpicker" multiple ng-model="myPets" ng-options="pet.id as pet.name for pet in arrayFromApi">
<option value="">Select...</option>
</select>
<!--<select ng-repeat="pets in arrayFromApi" class="selectpicker" multiple>
<option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
</select>-->
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };
$scope.arrayFromApi = function() {
......
this function get id names
}
$scope.mixData = function(){
$scope.model.pets = $scope.myPets;
};
});
</script>
如果將select
作為角度標准ng-options
與此屬性一起使用,則可以更好地處理視圖中的所有內容,並將多類型返回數組作為{id: n}
var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.model = {}; //from api $scope.arrayFromApi = [{ id: 1, name: 'test' }, { id: 2, name: 'test2' } ]; $scope.getDetails = function() { console.log($scope.model); } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <input type="text" ng-model="model.name" placeholder="Put your name..." /> <input type="text" ng-model="model.age" placeholder="Put your age..." /> <!--Select pets for model person--> <select ng-model="model.pets" ng-options="{id: item.id} as item.name for item in arrayFromApi" multiple></select> <button ng-click="getDetails()">save</button> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.