Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data between AngularJS controllers? [duplicate]

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'];
like image 930
Foo Stack Avatar asked Jun 02 '13 06:06

Foo Stack


People also ask

What is the efficient way of sharing data between controllers?

Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.

How can I pass one controller data to another controller in AngularJS?

We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it. Service : app. service('setGetData', function() { var data = ''; getData: function() { return data; }, setData: function(requestData) { data = requestData; } });

Can we have two controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.


1 Answers

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.

like image 105
Dan Avatar answered Sep 23 '22 03:09

Dan