Here is the service I created to fetch user details:
angular.module('app')
.factory('userDetailService', function($http) {
var userData = {};
function getUserDetails(userId) {
if (userId) {
return $http.get("/users/" + userId).success(function(data) {
angular.copy(data[0], userData);
});
}
}
return {
userData: userData,
getUserDetails: getUserDetails
}
})
In Controller 1
, I am using this service successfully to retrieve relevant data:
$scope.getUserId = function(userId) {
if (userId) {
$scope.userData = userDetailService.userData;
userDetailService.getUserDetails(userId).success(function() {
console.log($scope.userData); //Prints valid user data
});
}
};
However, when I try to access userData
in Controller 2
:
$scope.userData = userDetailService.userData;
console.log($scope.userData); //Prints null
The value of $scope.userData
is null. Shouldn't I be able to access the data shared by the service between controllers? Why does it work in one controller but not in the other?
Interestingly, a modal dialog template in Controller 2
can access data with {{userData.first_name}}
and {{userData.last_name}}
. If this works, why is $scope.userData
null? What am I missing?
Edit:
Template 1:
<div id="myModal" ng-controller="Controller 1">
<modal-configure-user></modal-configure-user>
<a data-toggle="modal" data-target="#configureUserModal" href="#" ng-click="getUserId(user.id)" data-id="user.id">{{user.first_name + ' ' +user.last_name}}</a>
</div>
Template 2:
<div ng-controller="Controller 2" id="configureUserModal">
</div>
Both are modal dialog windows.