繁体   English   中英

从AngularJS中的数组中获取对象的正确方法

[英]Proper way to get an object out of an array in AngularJS

我刚刚开始使用AngularJS,想知道是否有更好的方法可以做到这一点:

我有一家工厂,向我提供代表产品的一系列对象。 (目前已进行硬编码-产品最终将通过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;
});

假设使用/ product / wireframe-kit之类的路由,以下是路由器当前的设置方式:

app.config(function($routeProvider){
    $routeProvider.
        when('/product/:slug', {
            templateUrl: 'template/product.html',
            controller: 'productController'
        });
    }
}); 

然后,我使用url中的段从控制器中的此数组中检索正确的产品:

app.controller('productController', function($scope, $routeParams, Products){
    Products.forEach(function(product){
        if( product.slug == $routeParams.slug) {
            $scope.product = product;
        }
    });
});

我关心的是控制器中的forEach循环-我确定必须有一种更简单,更有效的方法来解析此积数组以获取所需的对象。 有任何想法吗?

您可以将api更改为返回对象(如果所有产品都具有唯一的子弹)。 这样,您可以通过密钥(子弹)名称访问产品:

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

如果我们通过实用的方式设置了REST API,

/products是您的“收藏”

/products/:id成为您的“模特”

在使用静态数据时,仍然有必要将数据作为静态文件放置在服务器上,以模仿相关Web文件夹中的这些模式。

然后使用Angular,您可以设置路由以获取对这些“端点”的请求

  • /products/ -给您$scope.collection
  • /products/<id of products> -为您提供$scope.model

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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