为什么Angularjs服务返回的是字符数组而不是对象数组

Why does Angularjs Service Return a Character Array instead of an Array of Objects?

本文关键字:数组 对象 Angularjs 字符 返回 为什么 服务      更新时间:2023-09-26

我正在使用一个服务(.factory)来保存一组对象/项,这些对象/项由多个控制器更新,然后由每个控制器收回数据。每次添加新的数据数组时,我都会将其推送到数组中。然而,当我试图在控制器中加载一个数组以便在视图中显示它时,它会返回一个字符数组,这使得无法使用ng repeat来迭代值。

// controllers.js
angular.module('myapp.controllers', [])
.controller('MainCtrl', function($scope, MainService) {
  $scope.mainItems = MainService.all(); // Why does this return a char array?
  // get the count
  $scope.getCount = function(item){
      return TempOrder.getCount(item);
  }
  // add an item
  $scope.addItem = function(item){
      TempOrder.addItem(item);
      return TempOrder.getCount(item);
  }
})
.controller('SecondaryCtrl', function($scope, MainService) {
   $scope.items = MainService.all(); // Why does this return a char array?
  // get the count
  $scope.getCount = function(item){
      return TempOrder.getCount(item);
  }
  // add an item
  $scope.addItem = function(item){
      TempOrder.addItem(item);
      return TempOrder.getCount(item);
  }
});

这是我的服务

// services.js
angular.module('myapp.services', [])
.factory('MainService', function() {
orderItems = [];
return {
   all: function() {
       return orderItems;  // Why does return a char array???
   },
   getCount: function(item){
      var count = 0;
      for (i = 0;i<orderItems.length;i++) {
        if (orderItems[i] === item ){
          count++;
        }
      }
     return count;
   },
   addItem: function(item) {
      orderItems.push(item);
   }
  }
});

我已经更新了您的上述代码,但由于某些原因,在此处添加代码片段时获得了module not found

请参阅此fiddle以获取您的解决方案,我不确定出了什么问题,但可能是您唯一传入item.name或任何密钥的html,也可能是您没有在controller中初始化$scope.item = {},这就是为什么它仍然未定义,angular无法绑定到它。记住angular不会绑定到控制器引导程序上未定义的值

感谢I_Debug_Mything的帮助。我意识到在我看来我没有正确地传递item对象。当以错误的方式传递时,它不会作为对象传递,因此无法引用项的属性。正确的方式将项作为对象传递,因此我可以在函数中访问item.name之类的东西。

错误的方式

<div ng-controller="MainCtrl">
    <div ng-repeat="item in items track by $index">
        <button ng-click="addItem('{{item}}')">{{Item.name}}</button>
    </div>
</div>

正确的方式

<div ng-controller="MainCtrl">
    <div ng-repeat="item in items track by $index">
        <button ng-click="addItem(item)">{{Item.name}}</button>
    </div>
</div>