0
我正在构建问卷并试图弄清楚如何让我的'activeQuestion'仅使用ng-click为每个问题显示一个项目。
我可以使用ng-repeat获取所有要显示的项目。这是获取json并将其传递给控制器的最佳方式,因为我已经看到了很多示例,在控制器中获取json。感谢任何帮助。
service.module.js
angular.module('services', [])
.service('getQuestion', ['$http', '$q', function($http, $q){
var question = this;
question.questionList = {};
question.viewAll = function() {
var defer = $q.defer();
$http.get('/data/data.json')
.success(function(res){
question.questionList = res;
defer.resolve(res);
})
.error(function(err){
defer.reject(err);
})
return defer.promise;
}
return question;
}]);
controller.js
angular.module('app.question')
.controller('QuestionController', ['$scope', '$log','getQuestion',
function ($scope, $log, getQuestion) {
var vm = this;
vm.activeQuestion = 0;
vm.init = function() {
vm.getAll();
}
vm.getAll = function() {
getQuestion.viewAll()
.then(function(data){
// success
$log.log(data);
vm.questionList = getQuestion.questionList;
}, function(){
// error
})
}
vm.init();
// Goes to the next question
vm.next = function() {
return vm.activeQuestion +=1;
}
}]);
data.json
[
{
"sectionTitle": "",
"title": "Select each of the following that apply to you"
},
{
"sectionTitle": "Income",
"title": "Enter any income you get. Leave them blank if they don't apply to you."
},
{
"sectionTitle": "Savings",
"title": "If you regularly put money into a pension, savings or investments, enter the amount here."
}
]
HTML
<div class="main-content__right" ng-controller="QuestionController">
<div class="question" ng-repeat="element in question.questionList track by $index" ng-show="$index == activeQuestion">
<div class="cabtool">
<h2 style="margin-top: 0;">{{$index}} {{element.sectionTitle}}</h2>
<p>{{element.title}}</p>
</div>
</div>
<button type="button" class="btn btn-primary right-button-icon" style="float:none" ng-click="next()">Next</button>
</div>
我会做什么是创建一个函数,返回基于参数的特定项目,如您在** getquestion **服务中使用activeQuestion的id。仅在一个项目中重复数组是没有意义的。 – katmanco
所以你的意思是添加ID:...对于json文件中的每个项目,用element.id替换'track by $ index'。 – NiseNise