Kamil Zaharan Kamil Zaharan - 2 years ago 110
AngularJS Question

Angularjs - Service doesn't store data between controllers

I've got a problem in my angular application which is service, a factory, for storing data between controllers. In one view I'm pushing objects to a list and I'm sure it proceeds, but whenever I go to another view (with a new controller) the list is empty.


'use strict';

var services = angular.module('services', ['ngResource']);

services.factory('participants', function () {
var participants = {};

participants.list = [];

participants.add = function(name, sirName, email, answer){
participants.list.push({name: name, sirName: sirName, email: email, answer: answer});

return participants;


'use strict';

var cont = angular.module('controllers', ['services']);

cont.controller('lottery1Ctrl', ['$scope', 'participants', '$location', '$log',
function ($scope, participants, $location) {
$scope.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
return function(){
controller.content = fileContent;

$scope.checkParticipants = function () {
if(participants.list.length == 0){
alert("Wgraj plik CSV")

$scope.csvToJson = function (text) {
var lines = text.split("\n");

for (var i = 1; i < lines.length; i++) {
var currentLine = lines[i].split(",");

var answer = currentLine[0];
var name = currentLine[1];
var sirName = currentLine[2];
var email = currentLine[3];
participants.add(name, sirName, email, answer);

cont.controller('lottery2Ctrl', ['$scope', 'participants', '$log',
function ($scope, $log, participants) {
$scope.getTotalParticipants = function () {
return participants.list.length;
cont.controller('ListCtrl', ['$scope', 'participants',
function (participants) {
var self = this;
self.participants = participants.list;


<h3>Participants number: {{getTotalParticipants()}}</h3>
<div ng-controller="ListCtrl as list">
<p ng-repeat="participant in participants.list">{{ participant.name }}: {{ participant.sirName }}: {{ participant.email }}: {{ participant.answer }}</p>

Output shows nothing but :::, and whenever I try to get length value of a list I get an error "cannot read property 'length' of undefined"

Thanks in advance!

Answer Source

I don't see anywhere where your list of participants is passed up to $scope object which is where you can bind it in your html or reference it from ng-repeat. While I can't comment on your entire program, it seems to me that you need to make a declaration in your controller such as :

    $scope.participants = [];

and then you should add your participants to that array. Try putting this in your code and see if it displays the dummy values on your web page, if so you probably need to tweek your functions so that array gets populated in your controller :

    $scope.participants = [{name:'Test1'},{name:'Test2'}];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download