我想在UI中从ng-repeat中保存选定的值(用户从下拉列表中选择它)并将其保存到变量中。
function saveToDb() {
console.log('in func')
var postToApi = [];
vm.newStudent.ethnic = [];
angular.forEach(vm.newStudent.ethnicity, function (value, data) {
vm.newStudent.ethnic.push({
ethnicity: value.ethnicity
});
});
var regNewStudent = {
ethnic: vm.newStudent.ethnic,
}
postToApi.push(regNewStudent)
console.log('Student Saved')
答案 0 :(得分:1)
您的选择是多个,因此当您在下拉列表中选择一个项目时,将是一个对象数组。
此示例显示了您的数据如何在var regNewStudent
中保存对象ethnic
是一个数组。
这是plnkr
<强> HTML 强>
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
<select ng-model="vm.newStudent.ethnicity" placeholder="Ethnicity" aria-label="Ethnicity" ng-model-options="{trackBy: '$value.code'}" multiple ng-options="opt as opt.name for opt in vm.listofEthnicity">
</select>
{{vm.newStudent.ethnicity}}
<button ng-click="vm.save()">Save</button>
</body>
</html>
<强> CONTROLLER 强>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
var regNewStudent = {
ethnic: ''
};
vm.listofEthnicity = [
{ "code": 111, "name": "New Zealand European/Pākehā" },
{ "code": 121, "name": "British / Irish" },
{ "code": 122, "name": "Dutch" },
{ "code": 123, "name": "Greek" }
];
vm.save = function() {
regNewStudent = {
ethnic: vm.newStudent.ethnicity,
};
// cause i dont have the postToApi to factory i just console it.
console.log(regNewStudent);
//postToApi.push(regNewStudent); //uncomment on your code.
};
});