9

如何将我在复选框中选择的项目与其他控制器一起存储?

我的尝试(见plnkr的意见):

script.js(控制器)

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'];
4

1 回答 1

4

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

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

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

于 2013-06-02T07:04:48.107 回答