Javascript 在AngularJS中从数组中获取对象的正确方法
我刚刚开始学习AngularJS,想知道是否有更好的方法: 我有一家工厂,为我提供一系列代表产品的对象。(目前这是硬编码的——产品最终将从RESTful API返回。) 假设路由为/产品/线框套件,以下是路由器当前的设置方式:Javascript 在AngularJS中从数组中获取对象的正确方法,javascript,arrays,angularjs,Javascript,Arrays,Angularjs,我刚刚开始学习AngularJS,想知道是否有更好的方法: 我有一家工厂,为我提供一系列代表产品的对象。(目前这是硬编码的——产品最终将从RESTful API返回。) 假设路由为/产品/线框套件,以下是路由器当前的设置方式: app.config(function($routeProvider){ $routeProvider. when('/product/:slug', { templateUrl: 'template/product.htm
app.config(function($routeProvider){
$routeProvider.
when('/product/:slug', {
templateUrl: 'template/product.html',
controller: 'productController'
});
}
});
然后,我使用url中的slug从控制器中的该数组中检索正确的产品:
app.controller('productController', function($scope, $routeParams, Products){
Products.forEach(function(product){
if( product.slug == $routeParams.slug) {
$scope.product = product;
}
});
});
我关心的是控制器中的forEach循环——我确信必须有一种更简单、更有效的方法来解析这个products数组以获得我想要的对象。有什么想法吗?您可以将api更改为返回对象(如果所有产品都有唯一的slug)。通过这种方式,您可以通过密钥(slug)名称访问产品:
如果我们实用地设置了RESTAPI,它会
/products
-成为您的“收藏”
和/products/:id
-成为您的“模特”
当您使用静态数据时,仍然值得将数据作为静态文件放在服务器上,以模拟相关web文件夹中的这些模式
然后,使用Angular,您可以设置路由以获取这些“端点”的请求
-为您提供/products/
$scope.collection
-为您提供/products/
$scope.model
var prodLength=Products.length;对于(var i=0;i
,这样就不需要进行任何迭代和比较不必要的对象值。我的想法是发出一次数据库请求来获取所有产品(假设~10个产品),然后在导航到产品详细信息页面时为自己保存另一个HTTP请求。正如您所说,您将来将使用rest api,这很可能是您希望使用的设置。这里的关键是,每个产品数组值都会从具有“id”值中受益,然后您仍然可以使用/route/id
作为路由
,并且仍然能够“选择”是从服务器重新提取还是使用您已有的集合
数组中的现有数据。您是什么web服务器使用?我目前正在Apache上运行,使用Mongo+PHP RESTful API。我理解您所建议的模式,但是对于这个项目,我希望获取所有10个产品,无论是在/products还是/product/:id上。这样,在两个视图之间导航将是即时的。
app.controller('productController', function($scope, $routeParams, Products){
Products.forEach(function(product){
if( product.slug == $routeParams.slug) {
$scope.product = product;
}
});
});
app.factory('Products', function(){
var products = {
'wireframe-kit': { slug: 'wireframe-kit', name: 'Wireframe Kit', price: 27 },
'ui-kit': { slug: 'ui-kit', name: 'UI Kit', price: 29 },
'ui-icons': { slug: 'ui-icons', name: 'UI Icons', price: 39 }
};
return products;
});
app.controller('productController', function($scope, $routeParams, Products){
$scope.product = Products[$routeParams.slug];
});