如何从 AngularJS 中的另一个控制器查找具有一个控制器 ID 的项目

How to look up items with id for one controller from another controller in AngularJS

我有两个控制器,第一个包含项目列表:

$scope.items = [{id:1, desc:'desc1'},{id:2, desc:'desc2'}...];

第二个绑定到显示所选项目列表的模板:

$scope.myitems = [1,2,3,...]; // ids only

 <div ng-repeat="item in myitems">
   {{item.id}} / {{item.desc}}
 </div>

如何从第一个控制器的项目列表中查找第二个控制器的ng-repeat中的项目描述?

你能在第一个控制器中为 $rootScope.items 赋值,然后尝试在第二个控制器中访问吗?

你可以尝试使用继承的概念:

var app = angular.module(....);

app.controller('FirstCtrl ', function($scope) {
  $scope.items = [{id:1, desc:'desc1'},{id:2, desc:'desc2'}...];
});

app.controller('SecondCtrl', function($scope, $controller) {
  $controller('FirstCtrl', {$scope: $scope}); // $scope.items now available

});

相对于 $rootScope 解决方案的优势:

  • 第二个控制器将始终可以访问 items,即使第一个控制器未实例化
  • items 数组只能由这两个控制器更改,不能由其他任何人更改

这种方法的主要缺陷是 SecondCtrl 将可以访问 FirstCtrl 的任何范围变量,而不仅仅是 items 数组

编辑。 恕我直言 Factory/Service @NexusDuck 提到的方法是最好的方法(组合继承)。

控制器之间共享数据最好通过 services/factories 实现,另一种方法是使用作用域继承。

1。 Factory/Service

angular.module('yourModule').factory('itemService', itemService);

    function itemService() {
         var items =  [{id:1, desc:'desc1'},{id:2, desc:'desc2'}...];
         return {
             findItemById: findItemById
         }
         
        function findItemById(id) {
            //logic to find item by id
        }
    }

将这个工厂注入到您的控制器中,并根据需要添加更多功能。

2。范围继承

这里的关键是嵌套你的 childcontroller,我认为它是带有 ids 的那个。

<div ng-controller="topCtrl">
   <div ng-controller="childCtrl">
      <div ng-repeat="item in myitems">
         {{item.id}} / {{item.desc}}
      </div>
   
   </div>
</div>

使用此选项,嵌套在视图中 topCtrl 中的任何控制器都可以访问 topCtrl 作用域变量。

第三种选择是将数据存储在 $rootScope 中,这实际上也是一种范围继承(除了独立指令范围之外的所有范围都继承自 rootScope),但这可能不是一个好主意你的用例。

您可以使用 $emit 和 $on。

例如: 在第一个控制器中添加

$scope.$emit('eventName', $scope.items);
};

同时传递 $scope.items.

在第二个控制器中添加

$scope.$on('eventName', function (event, args) {
    $scope.items = args;
});

args 保存 $scope.items 值并分配给第二个控制器中的 $scope.items,所以现在 ng-repeat 第一个控制器的 $scope.items 的值。