Retrieve a single element from a JSON file by making a $http.get request

Currently, I am working on a questionnaire project and facing an issue with displaying only one item for each question using ng-click.

Although I can display all items using ng-repeat, I am unsure if this is the most efficient way to fetch JSON data and pass it to a controller. I have noticed that many examples fetch JSON within the controller. Any suggestions would be appreciated.

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();

        // Proceeds 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>

Answer №1

Whenever I receive a list of items but only need to show one at a time, I implement 2 scope variables and utilize equal pointers.

Example in the Controller:

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]; // Set up the first element.
    };

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

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

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

    $scope.load();
});

Now you can utilize the current question element to display your question, while the list remains as "hidden background data".

    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on stopping slideToggle from opening and closing when clicked for the first time

When using the slideToggle function, I'm encountering an issue where the content div briefly shows on the first click but then immediately slides closed. Subsequent clicks work as expected and slide open correctly. This is the Jquery script I have be ...

How can I resolve the Error: Element type is invalid?

https://i.sstatic.net/9PehR.jpgI am encountering the error message displayed above, and I am uncertain about the cause of this issue. In the code snippet below, I am fetching data from a file named Data.js located in my root folder. When I run the app, I r ...

"Exploring the symbiotic relationship between Node.js and Express.js: an

I recently started learning Node.js and Express.js. I used the Express.js executable (express) to create an express application, which generated the following lines in app.js: ... var app = express(); http.createServer(app).listen(app.get('port' ...

When the field name is clicked, retrieve it and display it in a TOAST message

I am currently trying to extract information from a list displayed below (using onClick) where the data is retrieved from a JSON file and consists only of strings. However, I am facing difficulties in properly linking the array elements with the onClick fu ...

Page experiencing issues with JavaScript functionality

Here is a simple function that I am using to shake a form when the user's email is not valid: function shakeForm() { var l = 10; for( var i = 0; i < 10; i++ ) $("form").animate( { 'margin-left': "+=" + ( l = -l ) + 'px ...

Create a stylesheet document.write function that will never be true

While examining the source code of a webpage, I stumbled upon this intriguing piece of JavaScript right after the standard stylesheet declaration: <script type="text/javascript"> if('' != '') { document.write("< ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

Eliminate error messages from multiple input fields within the form by leveraging a directive

Within my form, I have multiple input fields for participant emails: <input name="participant{{$index}}email" type="email" ng-model="participant.email" ng-trim="true" required ng-minlength="1" ng-maxlength="255" ...

Displaying an alert on a webpage that shows a label input using JavaScript and

I'm currently working with HTML5 and JavaScript and I'm facing a challenge. I want to create a feature where users can input any word into a label, and when they click on a button, an alert is triggered with the given text. However, despite my ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

Can one convert to a boolean array in php?

I have a PHP script that I am sending data from JSON in serialized form using JQuery. PHP sees the POST data as a single associative array, which is really convenient. My question is, can I convert this data into a boolean array in PHP? And in general, is ...

Incorporating text sections into a div container and adjusting the width

Currently facing an issue with the canvas element on my project. <div id="app-container"> <div id="canvas-container"> <div id="canvas"></div> </div> </div> In the CSS stylesheet, the following styles ar ...

Identifying the language of characters written in English, Vietnamese, or Myanmar

My website is designed to support three languages - English, Vietnamese, and Myanmar. Users can submit content in any of these languages, and their submissions are stored in the database. When the content is displayed, I need to determine the language in w ...

What's causing my pug file to not show the data I retrieved?

In my index.js file, I have confirmed that the data is successfully retrieved using console.log. However, when I attempt to display this data in my view, I encounter an error that says: "Cannot read property 'feedUrl' of undefined. The followin ...

During the scraping process with Puppeteer in NextJs, the execution context was terminated, possibly as a result of a navigation

I'm currently developing an application to search for my music on websites that host illegal content, with the intention of requesting its removal later. While working with puppeteer, I encountered an issue when trying to submit a search query and re ...

How can you display an item in Angular JS only if there are elements in the ng-repeat loop

In my JSON data, a series of objects contain an array called "options". Some of these objects have items in this array while others do not. An example is shown below: { "label": "ORDERS", "enabled": true, "selected": true, "options": [ { ...

The result from noty.js is coming back as undefined

Recently, I started using noty.js but I encountered an issue while trying to execute the basic example for creating a noty. The error message I kept receiving was: Uncaught TypeError: Property 'noty' of object function (a,b){return new e.fn.init ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...