【问题标题】:AngularJS update data in ng-repeat from http requestAngularJS从http请求更新ng-repeat中的数据
【发布时间】:2017-03-18 07:22:58
【问题描述】:

我搜索了解决方案,但没有找到答案。我的问题是什么,在我的类别视图中,我有 init 函数,它发出 http 请求并从数据库中获取所有类别。我使用这些记录并制作 ng-repeat。但是,当我打开带有表单的模态以创建新类别时,当模态关闭并查看新类别时,我无法更新该 ng-repeat 视图。我以这种方式组织我的控制器、服务和视图:

查看

<div class="row main-body no-padding" ng-init="adminCtr.initCategory()">

    <div class="col-lg-4 margin-bottom-20" ng-repeat="category in adminCtr.allCategories">
        <div class="header-panel">
            <span class="category-headline">{{category.name}}</span>
        </div>
        <div class="main-form">
            {{category.id_cat}}
        </div>
    </div>

</div>

控制器:

function addCategory() {
        $mdDialog.show({
            templateUrl: 'app/views/modal/addCategory.html',
            clickOutsideToClose: false,
            controller: 'adminController',
            controllerAs: 'adminCtr'
        });
    }

    function initCategory() {
        adminService.initCategory().then(function (data) {
            vm.allCategories = data.categories;
        })
    }

    function createCategory(category) {
        adminService.createCategory(category).then(function (data) {
            if(data.success == false) {
                vm.categoryError = data.error;
            } else {
                vm.categoryError = '';
                cancelModal();
                initCategory();
                $location.path('/admin/category');
                $timeout(function () {
                    $mdToast.show(
                        $mdToast.simple()
                            .textContent('Kategorija je uspešno kreirana')
                            .position('top right')
                            .theme("success-toast")
                            .hideDelay(5000)
                    );
                }, 500);
            }
        })
    }

    function cancelModal() {
        $mdDialog.hide();
    }

服务:

function createCategory(category) {
        return $http.post('api/admin/createCategory', {
            category: category,
            idUser: $rootScope.globals.currentUser.idUser,
            token: $rootScope.globals.currentUser.token
        }).then(function(response) {
            return response.data;
        });
    }

    function initCategory() {
        return $http.post('api/admin/getAllCategories', {
            idUser: $rootScope.globals.currentUser.idUser,
            token: $rootScope.globals.currentUser.token
        }).then(function(response) {
            return response.data;
        });
    }

我尝试再次调用 init 函数来更新 vm.allCategories 但没有任何成功。

有人知道解决办法吗?

附:我尝试使用 $scope.apply() 但出现错误,顺便说一句,我使用 angular 1.6.2。

【问题讨论】:

  • 你能创建一个最小的工作 plnkr/jsbin/jsfiddle 吗?阅读mcve
  • data.category 包含什么?你能告诉我们示例数组/对象格式吗?
  • {"categories":[{"id_cat":"1","name":"fgfdgfd"},{"id_cat":"2","name":"dfgfdgdf"}, {"id_cat":"3","name":"dfgfdgdffdgdfg"},{"id_cat":"4","name":"dfgfdgdfg"},{"id_cat":"5","name":" dfdsfsdfsdfsd"},{"id_cat":"6","name":"sdfdsfsdfsdfsdfsd"},{"id_cat":"7","name":"dfgfdgfgfgfdgdf"}],"success":true}
  • 只是名称和id类别
  • 完全正确,我想避免刷新页面

标签: javascript angularjs angularjs-scope angularjs-ng-repeat


【解决方案1】:

在服务中删除承诺。您正在使用 promise 将响应缓存在控制器中。所以还需要在服务中添加一个承诺。

 function initCategory() {
        return $http.post('api/admin/getAllCategories', {
            idUser: $rootScope.globals.currentUser.idUser,
            token: $rootScope.globals.currentUser.token
        }) 
  }

在这样的控制器更新中

function initCategory() {
        adminService.initCategory().then(function (res) {
            vm.allCategories = res.data.categories; // in the response data comes inside data property. 
        })
}

【讨论】:

  • 不行,结果一样,我应该刷新页面才能看到新添加的类别
  • 你控制台vm.allCategories
  • 是的,在函数 initCategory 中并获取更新的记录,但视图保持不变
  • vm.allCategories = res.data.categories; 行后添加$scope.$apply() 并尝试一下
  • 我收到错误 $digest 已经在进行中,在我认为 1.4 版本之后不起作用
【解决方案2】:

如下更改您的 HTML 模板:

<div class="col-lg-4 margin-bottom-20" ng-repeat="category in adminCtr.allCategories track by category.id_cat">

和你的 JS

function initCategory() {
    adminService.initCategory().then(function(data) {
        $scope.$evalAsync(function(){
            vm.allCategories = data.categories;
        });
    })
}

演示

angular.module('myApp', []);

angular
  .module('myApp')
  .controller('MyController', MyController);

MyController.$inject = ['$scope', '$timeout'];

function MyController($scope, $timeout) {
  var vm = this;
  var a = [{
    "id_cat": "1",
    "name": "fgfdgfd"
  }, {
    "id_cat": "2",
    "name": "dfgfdgdf"
  }, {
    "id_cat": "3",
    "name": "dfgfdgdffdgdfg"
  }];
  var b = [{
    "id_cat": "1",
    "name": "fgfdgfd"
  }, {
    "id_cat": "2",
    "name": "dfgfdgdf"
  }, {
    "id_cat": "3",
    "name": "dfgfdgdffdgdfg"
  }, {
    "id_cat": "4",
    "name": "dfgfdgdfg"
  }, {
    "id_cat": "5",
    "name": "dfdsfsdfsdfsd"
  }, {
    "id_cat": "6",
    "name": "sdfdsfsdfsdfsdfsd"
  }, {
    "id_cat": "7",
    "name": "dfgfdgfgfgfdgdf"
  }];
  vm.allCategories = a;

  $timeout(function() {
    $scope.$evalAsync(function() {
      vm.allCategories = b;
    });

  }, 2000);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController as vm">
  <div ng-repeat="category in vm.allCategories track by category.id_cat">
    {{category.name}}
  </div>
</div>

【讨论】:

  • 不,还是一样,我确实需要刷新页面才能看到结果
  • 我收到了这个错误 $scope.$safeApply is not a function
  • 试试$scope.$evalAsync
  • 现在即使刷新页面后我也看不到记录
  • 最后我决定在空白页上创建位置路径,然后返回类别视图,这不是最好的,但比重新加载更好。
猜你喜欢
  • 1970-01-01
  • 2016-02-12
  • 2020-07-19
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 2016-10-19
  • 2017-12-22
  • 1970-01-01
相关资源
最近更新 更多