How do I store the items I've selected in a checkbox with other controllers?
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'];
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.
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; } });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With