Just dipping my toes into AngularJS and pondering on a more streamlined approach:
Currently, I have a factory that supplies me with an array of product objects. (For now, this data is hardcoded but will eventually be fetched 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;
});
For instance, when navigating to a route like /product/wireframe-kit, here's how the routing is currently configured:
app.config(function($routeProvider){
$routeProvider.
when('/product/:slug', {
templateUrl: 'template/product.html',
controller: 'productController'
});
}
});
To fetch the correct product based on the URL slug in the controller, I am presently utilizing a forEach loop:
app.controller('productController', function($scope, $routeParams, Products){
Products.forEach(function(product){
if( product.slug == $routeParams.slug) {
$scope.product = product;
}
});
});
I'm hesitant about the efficiency of the forEach loop in the controller - there must be a smoother way to extract the desired object from the products array. Any suggestions?