ANGULAR-UI-ROUTER: Resolve state from URL

前端 未结 4 1299
清酒与你
清酒与你 2020-12-16 20:14

I\'m making an app with dynamical states, and sometimes I need to resolve the state name from the url.

e.g.: I have /dashboard/user/12268 and I need to

4条回答
  •  春和景丽
    2020-12-16 21:01

    https://github.com/angular-ui/ui-router/issues/1651

    You can expose the internal state implementation by using the .decorator hook on $stateProvider. You can decorate any property of the state builder; I chose 'parent' arbitrarily.


    app.config(function($stateProvider) { 
      $stateProvider.decorator('parent', function (internalStateObj, parentFn) {
         // This fn is called by StateBuilder each time a state is registered
    
         // The first arg is the internal state. Capture it and add an accessor to public state object.
         internalStateObj.self.$$state = function() { return internalStateObj; };
    
         // pass through to default .parent() function
         return parentFn(internalStateObj); 
      });
    });
    

    Now you can access the internal state object using .$$state(), e.g.

    var publicState = $state.get("foo");
    var privateInternalState = publicState.$$state();
    

    Second, loop over each state in $state.get() and test them against your URL fragment.

    angular.forEach($state.get(), function(state) { 
      var privatePortion = state.$$state();
      var match = privatePortion.url.exec(url, queryParams);
      if (match) console.log("Matched state: " + state.name + " and parameters: " + match);
    });
    

提交回复
热议问题