NiseNise
NiseNise

Reputation: 1162

Show one array item from json file using $http.get

I am building a questionnaire and trying to figure out how I get my 'activeQuestion' to only show one item for each question using ng-click.

I can get all the items to display using ng-repeat. Is this the best way to fetch a json and pass it to a controller, as I have seen lots of examples, fetching the json in the controller. Appreciate any help.

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>

Upvotes: 0

Views: 79

Answers (1)

Artimus
Artimus

Reputation: 138

Every time I got a list of items but only want to display one of those at a time I use 2 scope variables and make use of the equal pointers.

Controller example:

angular.module('appName').controller('MyCtrl', function ($scope) {
    // Initialize scope variables for list and current item.
    $scope.questionList = [];
    $scope.currentQuestion = null;

    $scope.load = function () {
        $scope.questionList = questionList; // Wherever this may come from.
        $scope.currentQuestion = questionList[0]; // Setup the first element.
    };

    /**
     * Registered on the ng-click binding for example.
     */
    $scope.next = function () {
        var index;

        index = $scope.questionList.indexOf($scope.currentQuestion);
        index += 1; // Forward to next element.

        if ($scope.questionList[index]) {
            $scope.currentQuestion = $scope.questionList[index];
        }
        else {
            // Finished, advance to the next page or something.
        }
    }

    $scope.load();
});

Now you can use the current question element to display your question and the list only serves as "hidden background data".

Upvotes: 1

Related Questions