6

I just started learning Angular and I've looked on SO for a solution to load a JSON file using angular and I've done what other people have posted a solutions but I cannot get the data from my json file to show for some reason.

my json file (test.json) is simple:

{
    "array": [
        {"thing": "thing1"},
        {"thing": "thing2"},
        {"thing": "thing3"}
    ],

    "name": "robert"
}

this is my js file:

var myMod = angular.module("myMod", []);

myMod.controller("myCont", function ($scope, $http) {
    $scope.thing = "hi";

    $http.get("/test.json")
            .success(function (data) {
                $scope.stuff = data.array;
                $scope.name = data.name;
            })
            .error(function (data) {
                console.log("there was an error");
            });
});

and i'm trying to just display the name like this but only {{name}} shows:

<html ng-app="myMod">
    <head>
        <script src="angular.js"></script>
        <script src="testing.js"></script>
    </head>

    <body ng-controller="myCont">
        {{stuff}}
    </body>
</html>
4
  • what does your network tools show? Commented Jun 24, 2016 at 18:49
  • Add a console.log in the .success to see if it is called Commented Jun 24, 2016 at 18:50
  • nothing appeared in the console. the error was error: [$injector:unpr] Unknown provider: $htmlProvider <- $html <- myCont Commented Jun 24, 2016 at 18:53
  • @winsticknova check at the answer added below.. Commented Jun 24, 2016 at 18:57

3 Answers 3

5

I think you had typo, you should inject $http(responsible to make an ajax call) dependency instead of $html(doesn't exist in angular)

You should change code this way.

myMod.controller("myCont", function ($scope, $html) {

to

myMod.controller("myCont", function ($scope, $http) {
Sign up to request clarification or add additional context in comments.

2 Comments

yeah that worked! don't know why I was typing $html
I think you are missed $html
0

As Pankaj Parkar has stated, $http is what you need.

Here is a plunker I created with it working: http://plnkr.co/edit/d0DDU29uitMcwK6qA7kx?p=preview

app.js file with $http instead of $html:

var myMod = angular.module("myMod", []);

myMod.controller("myCont", function ($scope, $http) {
    $scope.thing = "hi";

    $http.get("test.json")
            .success(function (data) {
                $scope.stuff = data.array;
                $scope.name = data.name;
            })
            .error(function (data) {
                console.log("there was an error");
            });
});

Comments

0

If anyone trying this is getting the error:

$http.get(…).success is not a function

Apparently the syntax changed for Angular >1.6. The accepted answer here has new syntax: $http.get(...).success is not a function

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.