Pregunta

I'm trying to play around with allowing controllers to share variables using a factory. I've played around with my code quite a bit, and I do understand that $broadcast should be avoided. This is purely an educational exercise. I've tried many different methods of allowing a controller to run a function from my factory and I continually get the error "has no method 'login'"

I'm trying to allow my userController to call on the factory to $broadcast that is has a new user variable so that the header controller can catch it and update itself once a user has logged in.

    angular.module('app.user').factory('SessionService', function ($rootScope) {
    var data = {};
    data.user = null;
    data.login = function (user){
        this.user = user;
        $rootScope.$broadcast('userLoggedIn');
        return user;
    };

    return data;
    });

UserController:

angular.module('app.user').controller('UserController', ['$scope', '$routeParams', '$location', 'Global', 'UserService', '$q', 'SessionService',
function ($scope, $routeParams, $location, Global, UserService, $q, SessionService) {
    $scope.global = Global;
    $scope.selectedUsers = [];
    $scope.users = [];
    $scope.updateSessionUser = function(user){
        SessionService.login(user);
    }

    //CREATE NEW USER
    $scope.createUser = function (user, callback) {
        var newuser = new UserService({
            email: user.email,
            password: user.password1,
        });
        newuser.$create({}, function (response) {

            if (response.message) {
                alert(response.message);
            } else {
                $scope.updateSessionUser.login(response.user);
                $location.path('/account/order');
            }
        }, function (response) {
            alert("Error communicating with the website! ");
        });
    };

    }]);

Ignore poor programming. I'm constantly optimizing and fleshing out code once I have core concepts down.

¿Fue útil?

Solución

Try replacing

$scope.updateSessionUser.login(response.user);

with

$scope.updateSessionUser(response.user);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top