在 AngularJS 控制器之间共享数据? [英] Sharing data between AngularJS controllers?

查看:26
本文介绍了在 AngularJS 控制器之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I store the items I've selected in a checkbox with other controllers?

我的尝试(查看 plnkr 以了解视图):

My attempt (see the plnkr for views):

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

推荐答案

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

When you reference the CooSelection service, you are expecting an array, but the factory returns an object. You could do this instead:

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

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

Also, in your DebugCooList controller, your scope property does not match the name of the variable you are checking in the view. The controller code assigns to coo_selection but the view checks coo_list_selection, so you'll need to change one to match the other.

这篇关于在 AngularJS 控制器之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆