我有一个ng-model="award.myProperty"
的表格。有一些输入和texareas。在我的服务中,我有一个用于文本区域的数组:
allQuestions = [
id: 'XXX', question: 'some text',
id: 'YYY', question: 'some text',
id: 'ZZZ', question: 'some text',
];
我的目标是从文本区域以这种结构获取数据
questions: [{
'XXX': 'data from textarea1',
'YYY': 'data from texarea2',
'ZZZ': 'data from textarea3',
}];
我尝试将ng-repeat与ng-model
一起使用,但是ng-model
不会返回ID。如果我将$index
与ng-repeat
一起使用,则会得到一个数组:
[{ 0: 'data from textarea1',
1: 'data from textarea2',
2: 'data from textarea3',}]
结构很好,但这不是我的ID来自服务。
服务
const allQuestions = [
{ id: 'XXX', question: 'question1' },
{ id: 'YYY', question: 'question2' },
{ id: 'ZZZ', question: 'question3' },
];
getQuestion() {
return allQuestions;
},
CONTROLLER
$scope.allQuestions = awards_service.getQuestion();
$scope.award = {
description: '',
questions: [],
};
VIEW
<form name="awardForm">
<input ng-model="award.description"></input>
<div ng-repeat="question in allQuestions">
<textarea ng-model="award.questions"></textarea>
</div>
</form>
也许有比ng-repeat
更好的解决方案。
答案 0 :(得分:1)
在您的控制器中,将$scopre.award.questions
更改为:
$scope.allQuestions = awards_service.getQuestion();
$scope.award = {
description: '',
questions: [{}]
};
然后在视图中:
<form name="awardForm">
<input ng-model="award.description"></input>
<div ng-repeat="question in allQuestions">
<textarea ng-model="award.questions[0][question.id]"></textarea>
</div>
</form>
演示:
angular.module("myApp", [])
.controller('myCtrl', ['awards_service', '$scope', function(awards_service, $scope) {
$scope.allQuestions = awards_service.getQuestion();
$scope.award = {
description: '',
questions: [{}],
};
$scope.submit = function() {
console.log($scope.award);
// submit your form then reset the award object
// ...
$scope.award = {
description: '',
questions: [{}],
};
}
}])
.factory('awards_service', function() {
const allQuestions = [
{ id: 'XXX', question: 'question1' },
{ id: 'YYY', question: 'question2' },
{ id: 'ZZZ', question: 'question3' },
];
return {
getQuestion() {
return allQuestions;
}
}
});
.as-console-wrapper { height: 70px !important; overflow: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form name="awardForm" ng-submit="submit()">
<label>Description</label><br>
<input ng-model="award.description"></input><br>
<label>Questions</label><br>
<div ng-repeat="question in allQuestions">
<textarea ng-model="award.questions[0][question.id]" placeholder="Enter a question"> </textarea>
</div>
<input type="submit" value="submit" />
</form>
</div>
</div>