I'm just getting started with AngularJS and wondering if there's a better way to do this:
I have a factory providing me an array of objects representing products. (This is hard-coded for now - the products will eventually be returned from a RESTful API.)
app.factory('Products', function(){
var products = [
{ slug: 'wireframe-kit', name: 'Wireframe Kit', price: 27 },
{ slug: 'ui-kit', name: 'UI Kit', price: 29 },
{ slug: 'ui-icons', name: 'UI Icons', price: 39 }
];
return products;
});
Assuming a route such as /product/wireframe-kit, here's how the router is currently setup:
app.config(function($routeProvider){
$routeProvider.
when('/product/:slug', {
templateUrl: 'template/product.html',
controller: 'productController'
});
}
});
I'm then using the slug from the url to retrieve the correct product from this array in the controller:
app.controller('productController', function($scope, $routeParams, Products){
Products.forEach(function(product){
if( product.slug == $routeParams.slug) {
$scope.product = product;
}
});
});
My concern is with the forEach loop in the controller - I'm sure there's got to be an easier, more efficient way to parse this products array to get the object I want. Any ideas?
var prodLength = Products.length; for (var i = 0; i < prodLength; i++){if( Products[i].slug == $routeParams.slug) {$scope.product = Product[i]; break;}}That way you don't waist any iterations and comparing unnecessary object values.