无需重新加载即可获取stateParams

时间:2014-07-26 14:44:08

标签: angularjs angular-ui angular-ui-router

我正在使用角度ui路由器制作应用。

当导航到一个总是传递参数的特定状态时,我需要能够更改URL并更新参数而不重新加载视图。

在我的状态配置中,我使用:     reloadOnSearch:false

这样可以让我更新URL中的参数而无需重新加载页面。

但是,我需要在$ stateParams上收到有关这些更改的通知,以便我可以运行各种方法来处理新数据。

有什么建议吗?

谢谢,詹姆斯

2 个答案:

答案 0 :(得分:4)

这与我有关,所以我做了一些工作。

这是我使用reloadOnSearch的状态,但每次更新网址时都会触发一个函数。

      .state('route2.list', {
          url: "/list/:listId",
          templateUrl: "route2.list.html",
          reloadOnSearch: false,
          controller: function($scope, $stateParams){
            console.log($stateParams);
            $scope.listId = $stateParams.listId;
            $scope.things = ["A", "Set", "Of", "Things"];
            //This will fire off every time you update the URL.
            $scope.$on('$locationChangeSuccess', function(event) { 
                $scope.listId = 22;
                console.log("Update");
                console.log($location.url()); 
                console.log($stateParams);    
                });
          }
      }

在控制台中返回:

Update
/route2/list/7 (index):70
Object {listId: "8"} (index):71

$locationChangeStart$locationChangeSuccess可以让您到达目的地。请记住,即使在第一次加载时,您的位置功能也会始终触发。

this SO帖子和$location documentation

中获取的灵感

编辑2 根据{{​​1}}的Angular文档,ngRoute直到更改成功后才会更新。有可能ui-route也有类似的限制。由于我们正在破坏状态的分辨率,$routeParams永远不会更新。您可以做的只是模拟使用$stateParams首先传递$stateParams的方式。

像这样:

$urlMatcherFactory

范围实际更新,所以这是一件好事。要记住的是,除了将 .state('route2.list', { url: "/list/:listId", templateUrl: "route2.list.html", reloadOnSearch: false, controller: function($scope, $stateParams, $state, $urlMatcherFactory){ console.log($stateParams.listId + " :: " + $location.url()); $scope.listId = $stateParams.listId; $scope.things = ["A", "Set", "Of", "Things"]; $scope.$on('$locationChangeSuccess', function(event) { $scope.listId = 22; //For when you want to dynamically assign arguments for .compile console.log($state.get($state.current).url); //returns /list/:listId //plain text for the argument for clarity var urlMatcher = $urlMatcherFactory.compile("/route2/list/:listId"); //below returns Object {listId: "11" when url is "/list/11"} console.log(urlMatcher.exec($location.url())); var matched = urlMatcher.exec($location.url()); //this line will be wrong unless we set $stateParams = matched console.log("Update " + $stateParams.listId); console.log($location.url()); //properly updates scope. $scope.listId = matched.listId; }); } }) 设置为reloadOnSearch之外,你停止了所有内容的正常分辨率,因此您需要自己处理几乎所有内容。

答案 1 :(得分:1)

继Romans代码之后,我构建了一个返回当前状态的状态参数的服务

/**
 * Get parameters from URL and return them as an object like in ui-router
 */
eventaApp.service( 'getStateParams', ['$urlMatcherFactory', '$location', '$state', function(     $urlMatcherFactory, $location, $state ){
  return function() {

    var urlMatcher = $urlMatcherFactory.compile($state.current.url);
    return urlMatcher.exec($location.url());

  }

}]);
相关问题