Joel Jerushan
Joel Jerushan

Reputation: 655

Angular Reload another Controller after POST

as i mentioned in title, i just wanted to reload (without page refresh) another controller with updated data after POST here my Code .

There is no issue on saving data to database.

Script

var app = angular.module('userBase', []);
app.controller('listUsers', function($scope,$http) {
    $http.get("req.php")
        .then(function (response) {
            $scope.userloop = response.data.reqresponse;
        });

});

app.controller('addUsers', function($scope,$http) {

    $scope.buttonFire = function() {
        $http.post("add.php",{'name': $scope.name, 'email': $scope.email})
            .success(function(data, status, headers, config){

            });
    }

});

View

<div ng-controller="listUsers">
    <ul ng-repeat="x in userloop">
        <li>{{ x.Name }} - {{ x.Email }} </li>
    </ul>
</div>

<div ng-controller="addUsers">
    <p>Name: <input type="text" ng-model="name"></p>
    <p>Email: <input type="text" ng-model="email"></p>
    <span ng-bind="name"></span> and <span ng-bind="email"></span><br/>
    <button ng-click="buttonFire()">Send or Save</button>
</div>

Upvotes: 3

Views: 784

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13488

You can solve your problem with the help of events infrastructure:

app.controller('listUsers', function($scope,$http) {
    $scope.on('newuser', function(event, data){
        load(true);

        //or you can do this: (without row above, i.e. without performing 
        //request to the server)
        //$scope.$apply(function(){
        //     $scope.userloop.push(data);
        //}); 
    });

    var load = function(isEvent){
        $http.get("req.php")
          .then(function (response) {
                $scope.userloop = response.data.reqresponse;
                if(isEvent)
                     $scope.$digest();
          });
    };
    load();
});

app.controller('addUsers', function($scope,$http) {

    $scope.buttonFire = function() {
        var newuser = {'name': $scope.name, 'email': $scope.email};
        $http.post("add.php", newuser)
            .success(function(data, status, headers, config){
                  $scope.$parent.$broadcast('newuser', newuser);
            });
    }

});

Upvotes: 1

Related Questions