1

I'm still trying to learn angular JS and I am having trouble displaying the user I've just entered into the database to display on the next partial. I am able to display the other users but the data returned to me just after the user added just won't come out! I've learned a lot of ways to get it wrong, can someone show me how to do it right? here's my code.

Initial splash page

<div ng-controller="usersController">
<h1>Hello!</h1>
<h1>Please enter your name to join and share your ideas</h1>
<form>
    <input type="text" ng-model="newUser.name">
    <button ng-click="addUser()">Enter</button>
</form>

angular routes

var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: '../partials/main.html'
    })
    .when('/dashboard', {
        templateUrl: '../partials/dashboard.html' 
    })
    .otherwise({
        redirectTo: '/'
    });
});

the page I want to display the current user and all users added

<div ng-controller="usersController">
<h1>Welcome</h1>
<h1 ng-bind="currentUser.name"></h1>
<ul ng-repeat="user in allUsers">
    <li ng-bind="user.name"></li>
</ul>

my users controller

myApp.controller('usersController', function ($scope, usersFactory) {

var getUsers = function() {
    usersFactory.getUsers(function (data) {
        $scope.allUsers = data;
    })
}

$scope.addUser = function () {
    usersFactory.addUser($scope.newUser, function (data) {
        $scope.currentUser = {'name': data.name};
    })
}

getUsers();
})

my users factory

myApp.factory('usersFactory', function ($http, $location) {

var factory = {};

factory.getUsers = function (callback) {
        $http.get('/show_users').success(function (users) {
            callback(users);
        })
    }

factory.addUser = function (data, callback) {
    $http.post('/new_user', data).success(function (user) {
        callback(user);
        $location.path('/dashboard');
    })
}       
return factory;
})

any help is much appreciated!

Anptk
  • 1,125
  • 2
  • 17
  • 28

2 Answers2

0

Call the getUsers() each time you add a new user for allUsers to be updated.

$scope.addUser = function () {
    usersFactory.addUser($scope.newUser, function (data) {
        $scope.currentUser = {'name': data.name};
        getUsers();
    })
}
Gaurav Gupta
  • 1,929
  • 4
  • 21
  • 40
0

In javascript code is executed asynchronously. So getUsers() is called before the new user is finished adding to your database. To solve this problem you can include getUsers() function call inside the callback.

$scope.addUser = function () {
    usersFactory.addUser($scope.newUser, function (data) {
        $scope.currentUser = {'name': data.name};
        getUsers(); // <--
    })
}

Also look at angular promises https://docs.angularjs.org/api/ng/service/$q instead of using callbacks.

Shamal Perera
  • 1,611
  • 1
  • 18
  • 21