角度范围项目在项目更改后不适用

Angular scope items not applies after item change

本文关键字:项目 不适用 范围      更新时间:2023-09-26

我有项目服务、项目列表控制器和项目详细信息控制器:

.state('dashboard.items', {
        url: '/items',
        templateUrl: '/js/components/dashboard/items/items.html',
        controller:'itemsListCtrl'
      })
      .state('dashboard.items.details', {
        url: '/:id',
        templateUrl: '/js/components/dashboard/items/itemDetails.html',
        controller: 'itemDetailsCtrl',
        resolve:{
          items: function (ItemService) {
            if(!ItemService.items)
              ItemService.getAll().then(function (res) {
                ItemService.items = res.data;
              });
          }
        }
      })
app.factory('ItemService', function ($http) {
  var itemsFactory = {};
  itemsFactory.getAll = function () {
    return $http.get('/items');
  }
  itemsFactory.update = function () {
    itemsFactory.items[0].name = "sadasd";
  }
  return itemsFactory;
})
app.controller('itemsListCtrl', function($scope, $state, ItemService){
  if(!ItemService.items) {
    ItemService.getAll().then(function (res) {
      ItemService.items = res.data;
      $scope.items = ItemService.items;
    });
  }else{
    $scope.items = ItemService.items;
  }
})

app.controller('itemDetailsCtrl', function ($scope, items, ItemService) {
  $scope.item = ItemService.items[0];
  $scope.item.name = "abc" ;
  $scope.update = function(){
    ItemService.update();
  }
})

我有 ng 单击按钮,可以调用 edit() 函数。我使示例变得简单,在进行更新并编辑项目名称时,列表中显示的项目不会更改。我不知道我在这里错过了什么。该列表位于服务中,两个控制器都将其用于其目的。

我做错了什么?此方案的最佳做法是什么?

更新 1发现了一些奇怪的东西。当我在控制器初始化中编辑项目时,它会全局更改原始值。当它通过 edit() 方法发生时,它不会。什么好玩的?

谢谢。

$http.get 返回一个承诺,它将返回您的数据,所以在 .then 中你可以做你的事情,它会在完成后执行(异步)

$http.get('/items').then(function successCallback(response) {
 // this callback will be called asynchronously
 // when the response is available
 return response.data;//this is your data
}, function errorCallback(response) {
 // called asynchronously if an error occurs
 // or server returns response with an error status.
});