0

I am stuck. Somehow I can't get this working. I try to load data for a web-app from a (still local) JSON-file. A section of this JSON contains colors and looks like this:

{
  "colors" : {
    "1" : "yellow",
    "2" : "green",
    "3" : "red"
  },
  "stuff : {...}
}

I have a very basic HTML file with some header stuff. Scipts are loaded in the header. The interesting part looks like this:

<ul  ng-controller="ColorController">
  <li ng-repeat="(key,value) in colors" value="{{key}}">
    {{key}}: {{value}}
  </li>
</ul>

The corresponding Javascript:

var colors = {
    "1": "lyellow",
    "2": "lgreen",
    "3": "lred"
};

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

app.controller('ColorController', function($scope){

    $scope.colors = colors;

    $.getJSON('data.json')
        .then(function(res){
            $scope.colors = res.colors;
        });
})

I tried with a local version of colors first, therefore the variable colors. That worked well and produced the desired output. The I tried to switch to a local stored JSON. console.log showed a correct parsing. On a debug console, colors and res.colors looks the same. But the list on the page is not updated.

I'd guess it is something with timing, but I am not sure. Could somebody point me in the right direction?

Oliver
  • 596
  • 1
  • 7
  • 20

2 Answers2

1

jQuery's getJSON is performed outside angular's digest cycle, and thus the view isn't updated in then then of your ajax call. If you were to add a line with $scope.$apply() after your $scope variable assignment, the view would update (see plunker: https://plnkr.co/edit/HLSYl0pI2AZ15qf5T5WM?p=preview)

What I recommend, though, is to use angular's native $http.get to get the JSON. See plunker here for example: https://plnkr.co/edit/F7e5ECYbl91mYhF3g848?p=preview

angular.module('test', [])
.controller('testCtrl', function($scope, $http) {
  $http.get('colors.json')
  .then(function(response) {
    $scope.colors = response.data['colors']
  })
})
Fissio
  • 3,748
  • 16
  • 31
  • Would be apt to use `.success` in place of `.then`, coz personally I have faced some issues with `.then` – David R Jan 09 '17 at 13:39
  • .then was deprecated a few builds back (see http://stackoverflow.com/questions/35329384/why-are-angular-http-success-error-methods-deprecated-removed-from-v1-6) - what kind of problems did you face with .then? – Fissio Jan 09 '17 at 13:40
  • Yes. When we try to access a local `.json` file using the `$http` function the content were not rendering although the call was success. – David R Jan 09 '17 at 13:43
0

Try using the $timeout.

.then(function(res){
  $timeout(function (res) {
    // your code
  }, 0);
})

it will force angular to update the $scope.

Oksid
  • 60
  • 3