0
我想通過控制器共享一個對象數組posts.shoppingCart
。 MainCtrl
這個表達式的作品$scope.cart = posts.shoppingCart;
但是AuthCtrl
沒有。我的虛擬數據顯示沒有問題。不能從工廠共享對象
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');
});
};
}]);
你是絕對正確的!我不知道他們必須以相同的順序。它現在工作! – traveller