http - Angular.js $http $window.location 和全局变量

标签 http angularjs global-variables window.location

我正在尝试更新 $http 请求中的全局变量,重定向到新页面,然后打印该变量(出错时)。我不确定我这样做是否正确,但是当我尝试打印我的变量 ($rootscope.adHocLevel2) 时,它仍然是空的。 在js文件中

$scope.searchStep2 = function(option) { 
  $http.post($scope.url, { "option" : option}).
    success(function(data, status) {
      $scope.status = status;
      $scope.data = data;
      $rootScope.response = data; 
      })
    .
    error(function(data, status) {
      $scope.data = data || "Request failed";
      $scope.status = status;   
      $rootScope.response = 'Request failed';
      $rootScope.routeAd = {"route": "../adHoc/adhoc.html"};            
      $rootScope.addHocLevel2 = {"suggestedCategory": "Car","suggestedLocLabel": "world","suggestedShadowURL": "http://www.toyota.com/auris/hybrid"};
      $window.location=$rootScope.routeAd.route;            
});
};

在 Html 中,我正在尝试打印

<input type="text" ng-model="optLocation" value={{addHocLevel2}} />

提前致谢

最佳答案

根据上面的代码,您有 $window.location = $rootScope.routeAd.route 指向“../adHoc/adhoc.html”。这将重新加载应用程序,因此您会丢失 addHocLevel2 值。

您需要根据您的 routeProvider.when("/adhoc") 配置重定向到其哈希路由路径(例如 #/adhoc),而不是 ../adHoc/adhoc.html。

此外,我认为在 Angular 的单页应用程序中移动时,最好的方法是使用 $location.path(yourRoutePath) 而不是 $window.location ,除非您想完全更改位置(某处的新 URL)。

例如

您设置了 2 条路线:

app.config(function($routeProvider){
    $routeProvider
        .when('/main', { templateUrl:'/main/main.html',controller:'MainCtrl'})
        .when('/adhoc', { templateUrl: '/adHoc/adhoc.html',controller:'AdHocCtrl});
}

然后说你想从/main 重定向到/adhoc,它是这样的:

app.controller('MainCtrl',function($rootScope,$scope,$location,$http){
    $http.post(...).error(function(data,status){
       $rootScope.addHocLevel2 = {...};
       $location.path("/adhoc"); // this will 'redirect' you to adHoc/adhoc.html page
    }
})

更新:我更新了你的插件:http://embed.plnkr.co/01lfzd4Q4bFoSPAB4WIF/ 这就是我的做法——我相信还有其他方法。我使用 index.html 作为模板,并将 main.html 和 adhoc.html 作为您可以根据 URL 切换到的其他 2 个页面。

关于http - Angular.js $http $window.location 和全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892238/

相关文章:

flutter - 在父窗口小部件中访问子窗口小部件的变量(带有Dart的Flutter)

http - 将 HTTP 重定向到 HTTPS 时如何处理 Nginx 中的 400 错误

javascript - AngularJS 中的隐式/内联/$inject 依赖注入(inject)是如何工作的?

javascript - AngularJS 在 $http 调用循环中收集数据

javascript - 在 angular bootstrap ui typeahead 指令上触发按键事件

python - 在 Python 函数中引用(而不是赋值)全局变量。做法不好还是不好?

http - 服务器端代码执行流程(golang)

c# - 从 UserAgent 字符串创建 HttpBrowserCapabilitiesBase

ruby-on-rails-3 - 无法在 Ruby on Rails 中使用 XML 数据执行 http POST

c++ - gcc 插件 c c++ 查找全局非静态变量