Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service.

However, once I replaced the hard coded data with a .json file, the functionality stopped working. Even though I verified that the data was being queried correctly from the .json file within the controller.

Here is a snippet of the simple controller code:

(function (){
    'user strict';
    angular.module('myApp').controller('itemsCtrl',['$state','myappApi', itemsCtrl]);
    //constructor function
    function itemsCtrl($state, myappApi){
        var vm = this;

        myappApi.getItems(function(data){
            vm.items = data;
        });

        vm.selectItem = function(id){
            myappApi.setItemId(id);
            $state.go("app.item-detail");

        }
    };
})();

The Template code:

<ion-view ng-controller="itemsCtrl as vm">
    <ion-content class="has-header">
        <div class="list">
            <a class="item item-icon-right" ng-repeat="item in vm.items" ng-click="vm.selectItem(item.id)">
                <div class="row">
                    <div class="col item-thumbnail-left">
                        <img ng-src="vas-images/{{item.name}}.jpg">
                    </div>
                    <div class="col col-center">
                        <h3 class="blue-font">{{item.name}}</h3>
                        <p>{{item.desc}}</p>
                    </div>
                    <div class="col col-center">
                        <h4 class="blue-font-alt">Price:{{item.price}}$</h4>
                    </div>
                </div>
                <i class="icon ion-chevron-right icon-accessory"></i>
            </a>
        </div>
    </ion-content>
</ion-view>

The service code:

(function (){
    'user strict';
    angular.module('myApp').factory('myappApi',['$http', myappApi]);

    function myappApi($http){

        //function to get all the items.
        function getItems(callback){
            $http.get("app/items/data.json")
            .success(function(data){
                callback(data);
            });
        }

        //function to set the item ID.
        function setItemId(itemId){
            currentItemId = itemId;
        }

        return{
            getItems: getItems,
            setItemId: setItemId
        };
    };
})();

The contents of the .json file:

{
    "items" : [
    {"id":1005, "name":"item-one", "desc":"some text here and there", "price":100},
    {"id":1006, "name":"item-two", "desc":"some text here and there", "price":500},
    {"id":1007, "name":"item-three", "desc":"some text here and there", "price":600},
    {"id":1008, "name":"item-four", "desc":"some text here and there", "price":50},
    {"id":1009, "name":"item-five", "desc":"some text here and there", "price":20},
    {"id":1010, "name":"item-six", "desc":"some text here and there", "price":660}
    ]
}

Answer №1

It seems that there might be an issue with your data as the code below is functioning properly when used with a corresponding JSON file.

HTML

<body ng-controller="itemsCtrl as vm">
  {{ vm.items | json }}
</body>

JavaScript

var myApp = angular.module('myApp',[]);

myApp.controller('itemsCtrl', function(myappApi){
  var vm = this;
  myappApi.getItems(function(response){
    vm.items = response.data;
  });
});

myApp.factory('myappApi', function myappApi($http){
  return {
    getItems: function(callback){
      $http.get('data.json').then(callback).catch(callback);
    }  
  };
});

JSON

[{
  "name": "name",
  "desc": "desc",
  "price": 100
}]

Check out the related plunker here.

Answer №2

To start off, it is important to include the $scope in your controller. While some older versions of angular allow you to use this and $scope interchangeably, it is recommended to set up your controller as follows:

angular.module('myApp').controller('itemsCtrl',['$scope', '$state','myappApi', itemsCtrl]);
//constructor function
function itemsCtrl($scope, $state, myappApi){
    myappApi.getItems(function(data){
        $scope.items = data;
    });

    $scope.selectItem = function(id){
        myappApi.setItemId(id);
        $state.go("app.item-detail");
    }
};

Even if in your version of angular, this can be used instead of $scope, remember that you cannot reference the scope itself in the template - only its properties. Therefore, update this line:

<a class="item item-icon-right" ng-repeat="item in vm.items" ng-click="vm.selectItem(item.id)">

to

<a class="item item-icon-right" ng-repeat="item in items" ng-click="selectItem(item.id)">
            <div class="row">

Change item in items and selectItem(item.id) accordingly. Since vm is not a property on the scope, it cannot be accessed in the template.

(Make sure to replace all instances of vm.whatever throughout the template.)

--EDIT--

Apologies for my oversight regarding your ng-controller="itemsCtrl as vm" declaration. This may not be the solution to your issue. Nonetheless, I will keep this response here as it has helped others before.

Although I do not typically utilize the "controller as" functionality, consider avoiding naming conflicts by refraining from using var vm = this. It may not seem like an issue with scoping variables, but it's wise to steer clear of using the same name for both places.

Have you tried adding an .error handler to your $http call? This could potentially shed light on any errors occurring (such as being unable to locate a file).

Answer №3

Apologies if this question seems silly, but I recently made changes to my .json file and now it looks like this:

[
{"id":1015, "name":"product-a", "description":"some random text here and there", "cost":200},
{"id":1016, "name":"product-b", "description":"some random text here and there", "cost":800},
{"id":1017, "name":"product-c", "description":"some random text here and there", "cost":900},
{"id":1018, "name":"product-d", "description":"some random text here and there", "cost":70},
{"id":1019, "name":"product-e", "description":"some random text here and there", "cost":30},
{"id":1020, "name":"product-f", "description":"some random text here and there", "cost":990}
]

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

Guide on how to extract data from a local JSON file, retrieve images from the JSON object's URL, and store the image paths in a Model

I currently have the following JSON saved locally: { "country":[ { "alpha2Code":"AF", "alpha3Code":"AFG", "flag":"https://raw.githubusercontent.com/DevTides/c ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...

The Angular model finally refreshes its values after a console.log() is executed

UPDATE After further investigation, I discovered that the issue was not related to Angular itself, but rather a mistake in the update function within the node server controller. I have provided the fix below for reference, and decided to keep this questio ...

What is the best way to showcase an element within an array that matches a particular value or character?

I have obtained a JSON array from hxxp://best1st.info/Moviedb/json.php?m=tt2015381&o=json Here is a snippet of the array output: . and so on . . [STORYLINE] => On planet Earth in 1988, young Peter Quill ( ) sits in the waiting room of a hospital. ...

"Need assistance with npm ERR! Can anyone provide some help,

Recently, I created a notepad file in my directory called "package.json". Inside this file, I typed the following: { “name”: “Bot”, “version”: “1.0.0”, “description”: “My First Discord bot”, “main”: “bot.js”, “author”: ...

Issue encountered when setting up Webpack development server resulted in the failure to generate

Is anyone else experiencing difficulties when trying to create a static folder named "dist"? Package.json "scripts": { "start": "webpack-dev-server --open", "dev": "webpack --mode development --watch ./frontend/src/index.js --output ./frontend/static/fr ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...

Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently. Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective? Here is the imperat ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Warning message appears if date input field is left empty upon submission

After implementing angular-ui/ui-date for the date input and angular-auto-validate for form validation, I encountered an issue where the date input field shows a required message before submission. It seems that the problem may be caused by the built-in va ...

Tips for adding and verifying arrays within forms using Angular2

Within my JavaScript model, this.profile, there exists a property named emails. This property is an array composed of objects with the properties {email, isDefault, status}. Following this, I proceed to define it as shown below: this.profileForm = this ...

Encountering the error "Module 'aws-sdk', 'child_process', 'net' cannot be resolved" within the /node_modules/watchpack directory when using Webpack

I'm encountering issues while trying to compile my prod webpack file, specifically receiving 5-10 errors related to "cannot resolve module" aws-sdk and child_process. All of these errors seem to point back to the same path: "ERROR in (webpack)/~/watc ...

A guide on invoking a JavaScript function within a dropdown menu based on selection instead of change event

I need to automatically trigger a JavaScript function based on the value pulled from the dropdown options that are populated by a database. Currently, the JavaScript function only runs when I manually select an option on the front-end. Below is my code. I ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

Is it possible to capture and handle browser-specific errors that occur during an AJAX call? I am having trouble locating and capturing these errors

My goal is to thoroughly test an AJAX call for potential errors by deliberately breaking it in various ways. The error callback in jQuery ajax does not provide detailed information like what the browser logs, which is what I need to capture. For example, C ...

Guide to saving information to a file using angularJS

My variable contains a large amount of data similar to this: $scope.employees = [ {"firstName":"John", "lastName":"Doe", "city": "Bangalore","State":karnataka,}, {"firstName":"Anna", "lastName":"Smith", "city": "Hyderabad","State": ...