Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to a different page after POST using AngularJS

After searching and not coming up with a solution I am posting this code snippet for some help.

$scope.createAddress = function () {
    $http({
        method: 'POST',
        url: '/addressBook/api/Person',
        data: $scope.person,
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    }).success(function (data) {
        $location.path('/addressBook');
    });
}

After successfully posting I would like to redirect to a different page. $location.path is not accomplishing this. I have tried $scope.apply() as some others have had success with that. Am I missing something or not understanding what $location is used for? The code is being hit.

like image 422
Dennis Kiesel Avatar asked Sep 03 '13 19:09

Dennis Kiesel


People also ask

How to redirect to another page after submit in AngularJS?

Controller. btn = function () { var nam = $scope.name; var pass = $scope. passwww; var detail ={ "name" : nam, "password" : pass } console. log(nam + " and1 " + pass); $http({ url : "/daaa", method : "post", data : detail, headers : {'Content-Type' : 'application/json'} }) . then(function (response) { $location.

How to navigate to another page in AngularJS on button click?

You can use $location. path('/newPageUrl') to navigate to new page.

What is $window in AngularJS?

The $window service refers to the browser window object. It is globally available in JavaScript, so it causes testability problems. In AngularJS, it is not globally available. It includes various methods like alert box, prompt box, confirms box, etc.


2 Answers

Remember to inject the dependency to the controller:

                                                       |-- inject!
angular.module('myApp.controllers', []).               v
controller('AddressController', function ($scope, $location, $http) {
  $http({
    method: 'POST',
    url: '/addressBook/api/Person',
    data: $scope.person,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
  }).success(function (data) {
    $location.path('/addressBook');
  });
});
like image 117
Sgnl Avatar answered Oct 21 '22 10:10

Sgnl


There should be something listening on that path change, like a $routeProvider. Is that the case?

If you need a full page reload to that other (server-side) route you might try $window.location.href.

like image 27
Jair Trejo Avatar answered Oct 21 '22 09:10

Jair Trejo