0

I'm trying to use a simple Angular JS app to load data from a JSON file to a website but it does not work.

The JSON file is:

{"a": "a"}

The Angular app is:

var app = angular.module("app", [])
  .controller("ctrl", ["ser", function(ser) {
    var vm = this;

    ser.getInfo().then(function(data) {
      vm.data = data;
    });
  }])
  .service("ser", function() {
    this.getInfo = function() {
      return $.get("models/model.json");
    };
  });

The HTML is:

<div ng-controller="ctrl as ctrl">
  <p>{{ctrl.data.a}}</p>
</div>

I'm not getting any console errors. I think the problem is related to the lexical scoping for the controller due to the asynchronous getInfo().then() call in the controller, I checked vm inside the function and it is being loaded correctly but doesn't seem to change the ctrl object or Angular is not updating when it does.

I'm serving the app locally.

It works sometimes but most times it doesn't. I can get it to work using $scope but I'm trying to figure out why it's not working now.

JP Dolocanog
  • 451
  • 3
  • 19
juribe
  • 45
  • 5
  • "I'm serving the app locally". Do you mean from the file system? Because that won't work, since you can't use an HTTP request over the file system. See [this question's answers for more](https://stackoverflow.com/q/10752055/215552) – Heretic Monkey Jul 25 '17 at 21:05
  • @MikeMcCaughan I'm using simplehttpserver – juribe Jul 25 '17 at 21:10

2 Answers2

2

It appears you are using jQuery for the ajax. If you modify the scope outside of angular context you need to notify angular to run a digest

Change to using angular $http to avoid such issues

var app = angular.module("app", [])
  .controller("ctrl", ["ser", function(ser) {
    var vm = this;

    ser.getInfo().then(function(response) {
      vm.data = response.data;
    });
  }])
  .service("ser", ['$http', function($http) {
    this.getInfo = function() {
      return $http.get("models/model.json");
    };
  }]);

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

If it works with $scope that means that without it, Angular is not aware that you performed an asynchronous operation.

I think the following line is using jQuery: return $.get("models/model.json");

So even if you get your data from your function getInfo, it isn't synchronized with the view via vm.data = data;

Wing-On Yuen
  • 657
  • 5
  • 9