在AngularJS控制器之间共享数据?

时间:2013-06-02 06:21:42

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controller

如何将我选中的项目存储在带有其他控制器的复选框中?

我的尝试(请参阅the plnkr了解观点):

script.js(controllers)

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

myApp.factory('CooSelection', function () {
  return {selectedCoo: []}
})

function CooListCtrl($scope, CooSelection) {
  $scope.coos = {"Coos": ["spark", "nark", "hark", "quark"]};

  $scope.coo_list_selection = CooSelection;

  $scope.checkSelection = function (item) {
    if ($scope.coo_list_selection.indexOf(item) === -1) {
      $scope.coo_list_selection.push(item);
    } else {
      $scope.coo_list_selection.splice($scope.coo_list_selection.lastIndexOf(item), 1);
    }
  }
}

CooListCtrl.$inject = ['$scope', 'CooSelection'];

function DebugCooList($scope, CooSelection) {
  $scope.coo_selection = CooSelection;
}

DebugCooList.$inject = ['$scope', 'CooSelection'];

1 个答案:

答案 0 :(得分:3)

当您引用CooSelection服务时,您期望一个数组,但工厂返回一个对象。你可以这样做:

myApp.factory('CooSelection', function () {
    return [];    // Return an array instead of an object.
})

此外,在DebugCooList控制器中,您的scope属性与您在视图中检查的变量的名称不匹配。控制器代码分配给coo_selection,但视图会检查coo_list_selection,因此您需要更改一个以匹配另一个。