简体   繁体   中英

Proper way to get an object out of an array in AngularJS

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?

You can change your api to return object (if all products have unique slug). This way you can access products by key(slug) name:

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];
});

If we had a REST API set up pragmatically it would like

/products - being your 'collection'

and /products/:id - being your 'model'

As you are using static data, it would still be worth putting the data on the server as static files to mimic these patterns in relevant web folders.

Then with Angular you can set up the routes to do get requests for these 'endpoints'

  • /products/ - gives you $scope.collection
  • /products/<id of products> - gives you $scope.model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM