Loading JSON in Angular

Posted on

in

,

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 = [];

    $http.get('gems.json').success(function(data){
       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 *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031