2014-01-16 24 views
0

我有一個ctrl從API中取出一個json數組。在我的代碼中,我有一個ng-repeat循環遍歷結果。AngularJS:從一個數組中取出一個項目並添加到作用域

這是用於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(); 

    } 

回答

1

角作品如下:

赦:表達的評價是寬容未定義和空,不像在JavaScript ,>試圖評估未定義的屬性可能會生成ReferenceError或TypeError。

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

所以你只需要編寫:

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

,如果有一個零組件中的標題將是tool_type,如果沒有,沒有稱號。

+0

非常感謝Michael。奇蹟般有效。正是我需要的。多麼傳奇! – T2theC

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> 
+0

感謝您的迴應Ashton。雖然我確信這種方法可行,但我選擇了邁克爾斯的答案,因爲它更簡潔一些。感謝發佈 - 我相信我會在某個地方使用它! – T2theC

相關問題