刷新后AngularJS数据消失,更改页面后返回

时间:2015-09-14 15:11:40

标签: angularjs

我使用工厂存储来自$ http请求的数据。 我的问题是,当我重新加载页面时,所有数据都消失了(空表)。 但是一旦我切换当前页面(不同路线),数据就会再次返回。

重新加载页面后,我需要更改显示的数据?

这是我的工厂:

'use strict';

app.factory('dataFactory', function ($http) {
    var dataFactory = {};

    $http.get("data/hiragana.json").success(function(response){
        dataFactory.hiragana = response;
    });

    $http.get("data/katakana.json").success(function(response){
        dataFactory.katakana = response;
    });

    return {
        getHiraganaTable: function(){
            return dataFactory.hiragana;
        },
        getKatakanaTable: function(){
            return dataFactory.katakana;
        }
    };
});

这是我的控制者:

'use strict';

app.controller('HiraganaTableCtrl', function (dataFactory, $scope) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma',
      'dataFactory',
      '$scope'
    ];

    $scope.hiraganaTable = dataFactory.getHiraganaTable();

  });

这是我的观点:

  <table class="table table-striped table-bordered" >
    <tbody data-ng-repeat="group in hiraganaTable">
        <tr>
            <td data-ng-repeat="hiragana in group.Hiragana" data-toggle="tooltip" data-original-title="{{hiragana.Romaji}}" data-container="body">{{hiragana.Symbol}}</td>
        </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

This is because you're trying to access async code in a sync way. The $http method returns a promise. So you could try something like this:

Service:

'use strict';

app.factory('dataFactory', function ($http) {
    return {
        getHiraganaTable: function() {
            return $http.get("data/hiragana.json");
        },
        getKatakanaTable: function() {
            return $http.get("data/katakana.json");
        }
    };
}); 

Controller:

'use strict';

app.controller('HiraganaTableCtrl', function (dataFactory, $scope) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma',
      'dataFactory',
      '$scope'
    ];

    dataFactory.getHiraganaTable().then(function(res) {
      $scope.hiraganaTable = res.data;
    });
});