简体   繁体   English

AngularJS:如何从动态URL绑定数据?

[英]AngularJS : How to bind data from dynamic url?

I'm newbie in AngularJS 我是AngularJS的新手

We expose our data through REST APIs 我们通过REST API公开数据

/shop/2/mum  

this url returns JSON and bind them like this 此网址返回JSON并像这样绑定它们

function ec2controller($scope, $http){
  $http.get("/shop/2/mum")
           .success(function(data){
                $scope.shopname = data.name;
                $scope.location = data.location;
                $scope.customer = data.customer;
    })

In html 在html中

<div class="shop">
  <ul class="list-group">
    <li class="list-group-item">
     <span class="shop-box">{{showname}}</span>
    </li>
    <li class="list-group-item">
     <span class="shop-box">{{location}]}</span>
    </li>
   </ul>
  </div>

This works fine ! 这很好!

Now, we need to have a dynamic URL like 现在,我们需要有一个动态网址,例如

/shop/<user-id>/<location>

And i need to pass this url when i select an option from drop-down box, set the value in {{shopname}} , {{location}} accordingly. 当我从下拉框中选择一个选项时,我需要传递此URL,并在{{shopname}}{{location}}中相应地设置值。 How to do this please guide me ? 如何做到这一点,请指导我?

Thanks 谢谢

In your app.js you would have defined a series of routes that ui-router knows about. 在您的app.js中,您将定义ui-router知道的一系列路由。 These routes can have dynamic sections. 这些路线可以包含动态部分。 In your case you would need to do something like the following: 在您的情况下,您需要执行以下操作:

$stateProvider.state('shop', {
    url:"shop",
    abstract: true,
    views: {
        "body": {
            templateUrl: "partials/shop.jade",
            controller: "ShopController"
        }
    }
})
.state('shop.customer', {
    url: "/:customer",
    views: {
        "body": {
            templateUrl: "partials/shop.customer.jade",
            controller: "ShopCustomerController"
        }
    }
})
.state('shop.customer.location', {
    url: "/:location",
    views: {
        "body": {
            templateUrl: "partials/shop.customer.location.jade",
            controller: "ShopCustomerLocationController"
        }
    }
})

Note that this assumes /shop is set as an abstract meaning it wont be a resolvable route, you should follow this same standard if you want /shop/2 to also not resolve. 请注意,这假定/shop被设置为abstract这意味着它不会成为可解决的路由,如果您希望/shop/2也无法解析,则应遵循相同的标准。

Then in, for example the ShopCustomerLocationController, you can access the url parameters using the following: 然后,例如在ShopCustomerLocationController中,您可以使用以下命令访问url参数:

$state.params.location; // would return "mum"
$state.params.customer; // would return "2" <-- note string not integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM