【发布时间】:2016-07-02 21:55:45
【问题描述】:
编辑:更好地表述问题。我基本上是在研究如何使用存储在 $scope.item 中的变量(使用 $stateParams 从 URL 中获取)来访问 products JSON 数组中的相关对象。
好的,所以我使用了 ui-router 和 ng-ref 的组合,这样当您在“#/shop/”页面上单击产品时,它会创建一个 URL“#/shop/productname”,导航到该 URL 时会打开页面上的空白 div,用于包含 URL 中提到的产品的详细信息。
我遇到的问题,我确定我忽略了一些简单的事情,即如何根据 URL 中的名称获取相应的数据?这样我就可以显示存储在 JSON 对象中的产品名称/价格等?
任何帮助都会有很大帮助!很有可能我做错了,所以如果您觉得我可以选择更好的路径,请向我推荐正确的方向。
HTML:
shop.html 网址:#/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>
...
product.html 网址:#/shop/productName
<h1>item.name</h1>
<h2>item.price</h2>
App.js
angular.module('app', [
'ngAnimate',
'ui.router'
])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/shop');
$stateProvider
.state('shop',{
url: '/shop',
templateUrl: 'templates/shop.html',
controller: 'starWarsCtrl'
})
.state('shop.item',{
url: '/:item',
templateUrl: 'templates/three-quarter-page.html',
controller: function($scope, $stateParams){
$scope.item = $stateParams.item;
}
})
;
})
.controller('appCtrl', function ($scope) {
$scope.products = [
{
"name": "Product 1",
"index":1,
"link":"product1",
"price":"TBD",
}
];
$scope.selectItem = function (selectedItem){
_($scope.products).each(function (item){
item.selected = false;
if (selectedItem === item){
selectedItem.selected = true;
}
})
};
}) /*End Controller*/
});
【问题讨论】:
-
看起来你有来自 $scope.item 中 url 的项目。您只是在问如何使用该变量从 products 数组中获取对象吗?
标签: javascript angularjs angular-ui-router