Angular Js如何刷新新的工厂实例

时间:2017-12-27 06:23:58

标签: javascript angularjs angular-factory

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

// factory

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();

1 个答案:

答案 0 :(得分:0)

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),然后从那里发送你想要的工厂方法所需的页面,以便正确处理。

相关问题