【问题标题】:Angular Js how to refresh a new factory instanceAngular Js如何刷新一个新的工厂实例
【发布时间】:2017-12-27 06:23:57
【问题描述】:

我正在使用工厂来获取文件夹列表并将其显示在前端。同样在前端,我有可以将新文件夹添加到现有列表的表单。添加文件夹后,我想刷新我的工厂实例并显示更新的文件夹列表。

// 工厂

angular.module('myapp').factory('archiveService', ['$http', 'ApiUrl', function($http, ApiUrl) {
var archiveService = function() {
    this.repos = [];
    this.busy = false;
    this.page = 0;
};
archiveService.prototype.nextPage = function() {
    if (this.busy) return;
    this.busy = true;
    var url = ApiUrl.url + '/folders/?page=' + this.page;
    $http.get(url).then(function(res) {
        console.log(res);
        this.repos = res.data;
        if (items.repos == 0) {
            return;
        }
        this.page += 1
        this.busy = false;
    }.bind(this)).catch(function(data) {
    }.bind(this));
};
return {
    archiveService: archiveService,
}

}]);

// 这是我的控制器

angular.module('myapp').controller('archiveModalController', ['$rootScope', '$scope','archiveService', function($rootScope, $scope, archiveService) {

// I want to refresh this and show new data on update

    $scope.archivelist = new archiveService.archiveService();

}])

我想知道如何刷新以便获取新的更新数据

$scope.archivelist = new archiveService.archiveService();

【问题讨论】:

    标签: javascript angularjs angular-factory


    【解决方案1】:

    Angular 服务遵循singleton 模式,这意味着类的实例化仅限于单个对象。

    另外,由于您使用的是工厂:

    angular.module('myapp').factory('archiveService', [<dependencies>, function () {
        function nextPage() {
            //code here
        );
    
        return {
            nextPage: nextPage
        }
    
    }]);
    

    然后在您的控制器中,您只需:

    archiveService.nextPage();
    

    看到变量就位,我相信nextPage 可以简单地将页面作为参数接收,并且由于repos 是一个数组,我猜您打算将新获取的数据添加到该数组中? 这将是: this.repos.push(res.data;) 而不是 this.repos = res.data;

    重点是,每次您想要请求新数据时,您都应该从控制器调用正确的服务/工厂方法。

    所以在你的控制器初始化时,你只需要:

    (function init() {
        $scope.archivelist = archiveService.nextPage();
    })();
    

    尽管像我说的那样,你可能应该有一个像nextPage(1) 这样的初始值,然后从那里发送你想要正确处理的工厂方法的所需页面。

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      相关资源
      最近更新 更多