AngularJS工厂只调用一次 [英] AngularJS factory only called once

查看:58
本文介绍了AngularJS工厂只调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有工厂的测验类型的应用程序,可以从服务器获取问题列表:

I have a quiz type application with a factory that gets a list of questions from the server:

xoryApp.factory('questionService', function($http) {  
  return {
  qdata : function(callback) {
      $http.get('/static/question.json').success(callback);
  }
};
});

然后我像这样在控制器中将此工厂称为:

Then I call this factory in my controller like this:

questionService.qdata(function(results) {
    $scope.qdata = results;
});

然后,当我遍历问题时,我会在问题和答案部分视图之间来回切换.问题在于,每次加载问题视图时,都会从服务器重新加载工厂json.但是我希望它仅在加载应用程序时执行一次,而不是每次加载使用该控制器的局部视图时执行一次.

Then I switch back and forth between question and answer partial views as I loop through the questions. The problem is that every time the question view loads, it re-loads the factory json from the server. But I want it to only do that once when I load the app, not every time I load a partial view that uses that controller.

以角度实现目标的方式是什么?

What is the way that you achieve that in angular?

谢谢

推荐答案

之所以发生这种情况,是因为您正在控制器根函数内部调用工厂.每次加载控制器时,它将再次致电工厂.

THis happens because you are calling the factory inside the controller root function. Everytime that the controller was loaded, it will call the factory again.

我建议将此 plunker作为解决方案.也许这不是最好的,但是效果很好.

I propose this plunker as solution. Maybe it's not the best, but works fine.

在这种情况下,我将列表实例保存在工厂内部的变量上,并且只会加载一次.如果需要刷新,则可以调用其他函数来强制刷新到服务器端.

In this case I save the list instance on a variable inside the factory, and will loaded just once. If you need to refresh, then you can call a different function to force the refresh to the server-side.

有两种可能的解决方案:

Here a couple of possible solutions:

app.factory('questionService', function($http) {  
  var result;
  return {
      qdata : function(callback) {
          return result;
      },
      fecthData : function(callback) {
          result = $http.get('question.json').success(callback);
          return result;
      }
};
});

app.factory('questionService2', function($http) {  
  var result;
  return {
      qdata : function(callback) {
          if (!result) {
              result = $http.get('question2.json').success(callback);  
          }
          return result;
      },
      refreshQdata : function (callback) {
         return $http.get('question2.json').success(callback);  
      }
};
});

希望对您有帮助.

这篇关于AngularJS工厂只调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆