traveller traveller - 6 months ago 17
Javascript Question

Can't share object from factory

I am trying to share an object array

posts.shoppingCart
through controllers. Inside
MainCtrl

this expression works
$scope.cart = posts.shoppingCart;
but on
AuthCtrl
doesn't. My dummy data appear without problem.

var app = angular.module('test', ['ui.router']);

app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {

$stateProvider.state('home', {
url : '/home',
templateUrl : '/home.html',
controller : 'MainCtrl',
resolve : {
postPromise : ['posts',
function(posts) {
return posts.getAll();
}]

}
}).state('login', {
url : '/login',
templateUrl : '/login.html',
controller : 'AuthCtrl',
onEnter : ['$state', 'auth',
function($state, auth) {
if (auth.isLoggedIn()) {
$state.go('home');
}
}]

}).state('register', {
url : '/register',
templateUrl : '/register.html',
controller : 'AuthCtrl',
resolve : {
postPromise : ['posts',
function(posts) {
return posts.getShoppingCart();
}]

},
onEnter : ['$state', 'auth',
function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]

});

$urlRouterProvider.otherwise('login');
}]);


app.factory('posts', ['$http', 'auth',
function($http, auth) {
var o = {
posts : [],
shoppingCart : []
};

o.getAll = function() {
return $http.get('/catalog').success(function(data) {
angular.copy(data, o.posts);
});
};

o.getShoppingCart = function() {
return o.shoppingCart;
};

return o;
}]);



app.controller('MainCtrl', ['$scope', 'posts','auth',
function($scope, posts, auth) {

$scope.posts = posts.posts;
$scope.isLoggedIn = auth.isLoggedIn;
//setting title to blank here to prevent empty posts

$scope.sum = 0;
if ($scope.sum === 0) {
$scope.isDisabled = true;
}

$scope.cart = posts.shoppingCart;
var sum;
$scope.addPost = function(post) {
console.log(post);
$scope.cart.push({title: post.title, cost: post.cost});
var sum = parseInt($scope.sum,10) + parseInt(post.cost, 10);

$scope.sum = sum;
$scope.isDisabled = false;
};
}]);

app.controller('AuthCtrl', ['$scope', '$state', 'posts', 'auth',
function($scope, posts, $state, auth) {
$scope.user = {};
$scope.isLoggedIn = auth.isLoggedIn;
$scope.cart = [
{title:'Jani',cost:'Norway'},
{title:'Hege',cost:'Sweden'},
{title:'Kai',cost:'Denmark'}
];//posts.shoppingCart;

$scope.register = function() {
console.log($scope.user);
auth.register($scope.user).error(function(error) {
$scope.error = error;
}).then(function() {
$state.go('home');
});
};

$scope.logIn = function() {

auth.logIn($scope.user).error(function(error) {
$scope.error = error;
}).then(function() {
$state.go('home');
});
};
}]);

Answer
['$scope', '$state', 'posts', 'auth',
function($scope, posts, $state, auth) {

$state and posts are mixed up...