How to use Angular $location to set my new url location by changing its key-value params dynamically?

前端 未结 3 588
臣服心动
臣服心动 2020-12-28 18:30

Let\'s say I have a RESTful endpoint that accepts a range of facets to query data. Here\'s a few examples:

example.com/search?type=Doctor&location=Boston         


        
相关标签:
3条回答
  • 2020-12-28 18:46

    For the example above, the path() of your $location would be

    '/search' 
    

    and the root is

    'http://example.com' 
    

    Going back to his question, he did not ask to update the location with new path, he asked to update the location with new key-value pairs query dynamically!

    So to do that, it's just everyday jQuery $x(newX)!

    $location.search({type: x, location: y, radius: z}); 
    

    or

    $location.search({type: x, location: y}); 
    

    It's all jQuery !!

    If he wants to change the path from search to something else, he can do:

    $location.path('/otherPath'); 
    //his new location would be 'example.com/otherPath' 
    
    0 讨论(0)
  • 2020-12-28 19:03

    Using $location

    $location.path('/newValue').search({key: value});
    

    For Non AngularJS applications:

    You can use history.js to append parameters dynamically to the url. then split the url to retrieve the params and pass to angular:

    History.replaceState({state:1}, "State 1", "?Param1=something");
    

    I am suggesting history.js as IE until ver9 didnt support history object push state, if you are going to use IE10+ or google chrome, use the history state object to update the url. Hope it helps :)

    0 讨论(0)
  • 2020-12-28 19:03

    In fact, instead of using $location to call your data-service endpoint, a normal way to do that is

    <form id='searchForm' ng-submit="getDataService()" ng-controller="aController">
    <input ng-model="type"/>
    <input ng-model="location"/>
    <input ng-model="radius"/>
    <input ng-model="gender"/>
    <button type='submit'/>
    </form>
    

    and in getDataService() do a

    $http.get( serviceUrl, config ).success( ...
    

    with your serviceUrl being

    example.com/search/Facility/Wayne,NJ/3/f
    

    after parsing (using sprintf)

    0 讨论(0)
提交回复
热议问题