Refresh ui-router view when changing state settings?

What is the right way to update the ui-router view when changing state settings?

For example, if I have a state like:

.state("page.view", { url: "/pages/:slug", views: { "": { controller: "PageCtrl", templateUrl: "page-view.html", }, }, }) 

And a (wrong) controller that looks like this:

 .controller("PageCtrl", function($scope, $state) { $scope.page = loadPageFromSlug($state.params.slug); }) 

How can I load the new $scope.page when changing $state.slug ?

Note that the above does not work when switching from a page to another, because the controller starts only once when the first page loads.

+6
source share
3 answers

I would do something like this:

 .controller("PageCtrl", function($scope, $state) { $scope.$on("$stateChangeSuccess", function updatePage() { $scope.page = $state.params.slug; }); }); 

I would be curious if you find a better way - there might be some way to just look at the value of the slug state, but this purely and clearly expresses what you are observing.

+10
source

I'm really not quite sure if I don't miss something here, but based on the snippets shown in your question:

  • PageCtrl is associated with the state "page.view" and will be executed as many times as the "page.view" state is triggered
  • "page.view" declared the slug parameter - url: "/pages/:slug", , which will cause a state change - whenever it changes
  • If this is true (if I'm not observing something), we can use stateConfig - resolve
  • no need to use $state.params . We can use $stateParams (more UI-Router, as I personally said)

Well, if all this is correct, as shown in this working plunger , we can do it like this:

recognizer:

 var slugResolver = ['$stateParams', '$http' , function resolveSlug($stateParams, $http){ return $http .get("slugs.json") .then(function(response){ var index = $stateParams.slug; return response.data[index]; }); }]; 

Adjusted state def:

 .state("page.view", { url: "/pages/:slug", views: { "": { controller: "PageCtrl", templateUrl: "page-view.html", resolve: { slug : slugResolver }, }, }, }) 

And the PageCtrl parameter:

 .controller('PageCtrl', function($scope,slug) { $scope.slug = slug; }) 

Check out everything in action here.

+2
source

I had this problem in ui-router 0.2.14. After upgrading to 0.2.18, changing the parameter fires the expected $stateChange* events.

+1
source

Source: https://habr.com/ru/post/978758/


All Articles