< Back to AngularJS, Coding

Loading JSON in Angular

First we have our JSON file so like:

    "name": "Azurite",
    "price": 2.95,
    "canPurchase": true
}, {
    "name": "Bloodstone",
    "price": 5.95,
    "canPurchase": true
}, {
    "name": "Zircon",
    "price": 3.95,
    "canPurchase": false

To use it, instead of

app.controller('basicController', function(){
    this.products = gems;

where gems is a variable that has all the data in an array, we change it to:

app.controller('basicController', ['$http', function($http){
    var thisVar = this;
    thisVar.products = [];

       thisVar.products = data;

  } ] );

We add $http as an argument into the function and use the get method to get the JSON file. We also give a variable for ‘this’ so the method can use and assign out JSON data to whatever we want.

View the demo

Download the demo

Leave a Reply

Your email address will not be published. Required fields are marked *