当使用AngularJS服务尝试在两个控制器之间传递数据时,我的第二个控制器在尝试从服务访问数据时总是收到未定义的.我猜这是因为第一个服务执行$ window.location.href并且我认为这是清除服务中的数据?有没有办法让我将URL更改为新位置,并将数据保留在第二个控制器的服务中?当我运行下面的代码时,第二个控制器中的警报始终是未定义的.
app.js(定义服务的地方)
var app = angular.module('SetTrackerApp', ['$strap.directives', 'ngCookies']);
app.config(function ($routeProvider)
{
$routeProvider
.when('/app', {templateUrl: 'partials/addset.html', controller:'SetController'})
.when('/profile', {templateUrl: 'partials/profile.html', controller:'ProfileController'})
.otherwise({templateUrl: '/partials/addset.html', controller:'SetController'});
});
app.factory('userService', function() {
var userData = [
{yearSetCount: 0}
];
return {
user:function() {
return userData;
},
setEmail: function(email) {
userData.email = email;
},
getEmail: function() {
return userData.email;
},
setSetCount: function(setCount) {
userData.yearSetCount = setCount;
},
getSetCount: function() {
return userData.yearSetCount;
}
};
});
Run Code Online (Sandbox Code Playgroud)
logincontroller.js :(控制器1在服务中设置值)
app.controller('LoginController', function ($scope, $http, $window, userService) {
$scope.login …Run Code Online (Sandbox Code Playgroud) 我有一个名为saveInDB的函数.这将数据保存在数据库中.对象作为参数传递给函数.
$scope.SaveDB(iObj,function(iResult){
//after a sucessfull opreation in the DB. Now I need iObj to be passed to other controller.
// I have used $emit method
$rootScope.$emit('saveCallback');
})
Run Code Online (Sandbox Code Playgroud)
在其他控制器中,我需要访问iObj到其他控制器.我没有得到这个对象.在我的控制器中
var _save = $rootScope.$on('saveCallback',function(){
//i want same obj(which is used for saving ) to be access here.
})
Run Code Online (Sandbox Code Playgroud)