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

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

问题描述

我如何保存我在与其他控制器一个复选框选中的项目?

我尝试(见 的plnkr 的看法):

的script.js(控制器)

  VAR对myApp = angular.module('对myApp',[]);myApp.factory('CooSelection',函数(){
  返回{selectedCoo:[]}
})功能CooListCtrl($范围,CooSelection){
  $ scope.coos = {库斯:[火花,nark,联想起,夸克]};  $ scope.coo_list_selection = CooSelection;  $ scope.checkSelection =功能(项目){
    如果($ scope.coo_list_selection.indexOf(项目)=== -1){
      $ scope.coo_list_selection.push(项目);
    }其他{
      $ scope.coo_list_selection.splice($ scope.coo_list_selection.lastIndexOf(项目),1);
    }
  }
}。CooListCtrl $注射='$范围','CooSelection'];功能DebugCooList($范围,CooSelection){
  $ scope.coo_selection = CooSelection;
}。DebugCooList $注射='$范围','CooSelection'];


解决方案

在引用 CooSelection 服务,你期待一个数组,但工厂返回一个对象。你可以这样做,而不是:

  myApp.factory('CooSelection',函数(){
    返回[]; //返回的对象的阵列来代替。
})

此外,在你的 DebugCooList 控制器,则scope属性不匹配您在视图中检查变量的名称。控制器code分配给 coo_selection 但视图检查 coo_list_selection ,所以你需要改变一个符合其他。

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

My attempt (see the plnkr for views):

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

解决方案

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.
})

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天全站免登陆