使用AngularJS在POST后重定向到不同的页面

时间:2013-09-03 19:13:48

标签: post redirect angularjs location

在搜索并没有提出解决方案后,我发布此代码段以获得一些帮助。

$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');
    });
}

成功发布后,我想重定向到其他页面。 $ location.path没有实现这一点。我尝试了$ scope.apply(),因为其他一些人已经取得了成功。我错过了什么或不了解$ location用于什么?代码正在被击中。

6 个答案:

答案 0 :(得分:22)

请记住将依赖项注入控制器:

                                                       |-- 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');
  });
});

答案 1 :(得分:10)

应该听取路径变化的内容,例如$routeProvider。是这样的吗?

如果您需要将整页重新加载到其他(服务器端)路由,则可以尝试$window.location.href

答案 2 :(得分:1)

在你的控制器中添加$ location。像这样 例如:app.controller('yourController',函数($ scope,$ location,$ http等) 那么你的$ http应该是这样的。

$http({.... }).success(function(response) { $location.path('/your path')})

但请确保您必须在$ routeProvider配置中添加其他位置。 类似的东西:

app.config(['$routeProvider', 
   function($routeProvider) { 
   $routeProvider.
     when('/yournewlocation', {
      templateUrl: 'yourTemplate/yourpage'
   })
  }
])

就是这样。嗯,你知道我在说什么。

答案 3 :(得分:0)

.controller('regCtrl', ['$scope','$http', function($scope,$http) {

        $scope.submit = function() {
            alert("vf");

            $http.post("http://localhost:3000/insert",function(response,$location){
                if(response!= null){
                $location.path("/login");
            }
            else{
                $state.go('/register');
            }
            });
            }

            }]);

我的代码是这样的,我只在注册页面后得到json响应,而不是导航到另一个页面

答案 4 :(得分:0)

只需使用window.location.replace("/Home/Index");

答案 5 :(得分:-1)

最好的方法也是最轻的

window.location.replace("/home/list");