2

I am reading a JSON from a file in Angular. The content of the file is:

{
"mango":
[
{
  "id": 3,
  "image": "Mango1.jpg",
  "text": "I am mango 3"
},
{
  "id": 2,
  "image": "Mango2.jpg",
  "text": "I am mango 2"
}
]

}

I am reading it in my controller:

    $.getJSON("../json/list.json", function (json) {
    $scope.mangoLists = json;

When i output to console, it shows the mango object etc. But I am unable to output them to the UI by doing this:

    <div class="col-sm-6" ng-repeat="mango in mangoLists">
        {{mango.text}}
    </div>

Please assist.

1
  • And how exactly jQuery will trigger a digest cycle? Commented Jun 29, 2017 at 6:13

2 Answers 2

2

You need to also update the view of the controller data after calling $.getJSON by using $scope.$apply() like so:

$.getJSON("../json/list.json", function (json) {
    $scope.mangoLists = json;
    $scope.$apply();
} 

$scope.$apply() will trigger a digest cycle which will update the view.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked. Thank you so much. Why did i have to do this?
I am not 100% sure why you have to update the view, my guess would be it is because .getJSON is not part of Anugular's api so angular references inside the brackets {{ }} are not watching it.
0

Can you try as below i think you did something wrong in ng-repeat i hope this will help you

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">

  <div class="col-sm-6" ng-repeat="mango1 in mangoLists.mango">
        {{mango1.text}}
    </div>
</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
   $scope.mangoLists = {
"mango":
[
{
  "id": 3,
  "image": "Mango1.jpg",
  "text": "I am mango 3"
},
{
  "id": 2,
  "image": "Mango2.jpg",
  "text": "I am mango 2"
}
]
}
});
</script>

</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.