Javascript 根据ui路由器url选择JSON对象

Javascript 根据ui路由器url选择JSON对象,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,编辑:更好地表达问题。我主要研究如何使用存储在$scope.item中的变量,该变量使用$stateParams从URL获取,以访问产品JSON数组中的相关对象 好的,我使用了ui router和ng ref的组合,这样当您在/shop/页面上单击产品时,它会创建一个URL/shop/productname,当导航到该URL时,它会在页面上打开一个空白div,该div将包含URL中提到的产品的详细信息 我现在面临的问题是,我确信我忽略了一件简单的事情,那就是如何根据URL中的名称获取相应的数据?

编辑:更好地表达问题。我主要研究如何使用存储在$scope.item中的变量,该变量使用$stateParams从URL获取,以访问产品JSON数组中的相关对象

好的,我使用了ui router和ng ref的组合,这样当您在/shop/页面上单击产品时,它会创建一个URL/shop/productname,当导航到该URL时,它会在页面上打开一个空白div,该div将包含URL中提到的产品的详细信息

我现在面临的问题是,我确信我忽略了一件简单的事情,那就是如何根据URL中的名称获取相应的数据?这样我就可以显示存储在JSON对象中的产品名称/价格等

任何帮助都会有很大帮助!很有可能我在这件事上做错了,所以如果你觉得我可以选择一条更好的道路,请告诉我正确的方向

HTML:

shop.html URL:/shop

...
    <a ng-repeat="item in businesses | filter:{cat: cat} | filter:query" 
       ng-class="{active: item.selected}"
       ng-href="#/shop/{{item.link}}" 
       ng-click="selectedItem(item)">
        ...
    </a>
    <div ui-view></div>
...

这将为您获取所选项目,假设您的名称匹配

$scope.selectedItem = _.where($scope.products, {name: $scope.item});

我想,如果我是你,我会使用angular服务在控制器之间共享数据 该服务将为我处理数据,因此当我更改产品时,它将返回item对象

angular.module('app').factory('productsService', function () {
    self = this;
    self.products = [{
    "name": "Product 1",
    "index":1,
    "link":"product1",
    "price":"TBD",
   }];
   this.findByLink = function(link){
        // loop through your data
       //  returns what found or null 
   }
return {
     products : this.products 
     findById : this.findById
}

});
并将此服务注入每个控制器中

.controller('appCtrl', function ($scope, productsService) {
  $scope.products = productsService.products;
  ..........
和另一个

.controller('productCtrl', function ($scope, productsService, $stateParams) {

  $scope.item = productsService.findById($stateParams.link);
  ..........

看起来您在$scope.item中有来自url的项目。您只是在问如何使用该变量从products数组中获取对象吗?服务返回和productCtrl中的findById应该是findByLink吗?只是想弄明白这是从哪里来的。我的方法是通过循环数据来找到具有匹配链接的对象,但没有成功。你建议怎么做?我已经创建了factorie,虽然它工作得很好。
.controller('appCtrl', function ($scope, productsService) {
  $scope.products = productsService.products;
  ..........
.controller('productCtrl', function ($scope, productsService, $stateParams) {

  $scope.item = productsService.findById($stateParams.link);
  ..........