AngularJS:从数组中获取单个项并添加到范围

时间:2014-01-16 15:32:52

标签: api angularjs angularjs-scope

我有一个ctrl从API中提取json数组。在我的代码中,我有一个循环结果的ng-repeat。

这适用于PhoneGap移动应用程序,我想从数组中获取一个元素,以便我可以将其用作页面标题。

所以......我想在ng-repeat之外使用'tool_type'。

提前致谢 - 我不知道从这里开始。

示例json数据

[{  "entry_id":"241",
    "title":"70041",
    "url_title":"event-70041",
    "status":"open",
    "images_url":"http://DOMAIN.com/uploads/event_images/241/70041__small.jpg",
    "application_details":"Cobalt tool bits are designed for machining work hardening alloys and other tough materials. They have increased water resistance and tool life. This improves performance and retention of the cutting edge.",
    "product_sku":"70041",
    "tool_type": "Toolbits",
    "sort_group": "HSCo Toolbits",
    "material":"HSCo8",
    "pack_details":"Need Checking",
    "discount_category":"102",
    "finish":"P0 Bright Finish",
    "series_description":"HSS CO FLAT TOOLBIT DIN4964"},
    ..... MORE .....

Ctrl以调用API

// Factory to get products by category
    app.factory("api_get_channel_entries_products", function ($resource) {
        var catID = $.url().attr('relative').replace(/\D/g,'');

        return $resource(
            "http://DOMAIN.com/feeds/app_productlist/:cat_id",
            {
                cat_id: catID
            }
        );
    });

    // Get the list from the factory and put data into $scope.categories so it can be repeated
    function productList ($scope, api_get_channel_entries_products, $compile) {

        $scope.products_list = [];

        // Get the current URL and then regex out everything except numbers - ie the entry id
        $.url().attr('anchor').replace(/\D/g,'');

        $scope.products_list = api_get_channel_entries_products.query();

    }

2 个答案:

答案 0 :(得分:1)

Angular的工作原理如下:

  

原谅:表达式评估对于未定义和null是宽容的,与JavaScript不同,>在尝试评估未定义属性时,可以生成ReferenceError或TypeError。

http://code.angularjs.org/1.2.9/docs/guide/expression

所以你只需要写:

<title>{{products_list[0].tool_type}}</title>

如果有零元素,则标题将是tool_type,否则,没有标题。

答案 1 :(得分:0)

假设你想从列表中选择一个随机对象来使用这样的东西:

$scope.product-tool_type = products_list[Math.floor(Math.random()*products_list.length)].tool_type

然后显示结果只需使用

<h1>{{product-tool_type}}</h1>

或者:

<h1>{{products_list[Math.floor(Math.random()*products_list.length)].tool_type}}</h1>