angularjs - Angular routing based on a condition -


i have been trying find way implement angular routing routes based on condition rather link user clicks

route1 -> view1 route2 -> view2

to add complication, condition evaluated on result of service. retrieving set of items shopping cart checkout app. need shopping cart route view1 if number of items > 0. , different route if 0.

if (itemlistservice.getitems().length > 0) --> route1

else --> route2

and because of this, complication arises routing has wait until service result evaluated before loading corresponding view. in other words, promise of service has resolved.

i found following post suggested using 'resolve' configuration property within routeprovider, solves issue of waiting service response. i'm not sure if satisfies checking condition based on service response.

redirecting route based on condition

can me this? ui-router able implement better routeprovider?

yes,it can done using ui-router.for example,create 4 states: dashboard state,which links resolver state.on entering resolver state based on service's data can redirect appropriate state.this done of onenter hook of resolver state.

demo plunker

in plunker,

  1. click on parent in dashboard
  2. it navigate state child1 until items in service has values
  3. when items popped out navigate state child2

code:

 var myapp = angular.module('myapp', ["ui.router"]);  myapp.config(function($stateprovider, $urlrouterprovider) {   $urlrouterprovider.otherwise("/dashboard")   $stateprovider     .state('dashboard', {       url: '/dashboard',       templateurl: 'dashboard.html'     }).state('parent', {       url: '/parent',       resolve: {         statetogo: function(service) {           if (service.getitems().length > 0) {             return 'child1';           } else {             return 'child2';           }         }       },       onenter: function(statetogo, $state) {         $state.go(statetogo);       }     })     .state('child1', {       templateurl: 'child1.html',       resolve: {         service: function(service) {           return service;         }       },       controller: function($scope, service) {         console.log(service.getitems());         service.removeitem();         console.log(service.getitems());       }     }).state('child2', {       templateurl: 'child2.html'     }); });  myapp.factory('service', [function() {   var items = [1, 2];   return {     getitems: function() {       return items;     },     removeitem: function() {       items.pop();     }   }; }]); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -