I'm using resource in a factory to authenticate a user. I set $scope.user = User.user
in my controller and print out user.username
in my view. This all works like a champ except that I don't see the username until I refresh the page.
Here's my code simplified:
HTML
<div ng-app="app">
<div ng-controller="MainCtrl">
{{ user.username }}
</div>
</div>
Controller
app.controller('MainCtrl', ['$scope', '$location', 'User',
function ($scope, $location, User) {
$scope.user = User.user;
$scope.login = function(username, password) {
User.login({username:username, password:password},
function(user) {
$scope.user = user;
$location.path('/');
});
}
}]);
Factory
app.factory('User', ['$resource', '$location', function($resource, $location) {
var currentUser = {};
return {
login: function(user, success, error) {
$resource('/login').save(
user,
function(resp) {
user.isLoggedin = true;
currentUser = user;
success(user);
},
function(resp) {
alert(resp.data.message.text);
error(user);
}
);
},
user: currentUser
}
}]);
Figured it out. Basically I was trying to alter scope in the factory. Here's the working code:
Factory:
Controller
Now the view updates like it's supposed to.