簡體   English   中英

如何在范圍變量angularjs中獲取json數據

[英]how to fetch json data in scope variable angularjs

這是我的Json數據

"data": {
      "address": {
        "postalCode": "112629",
        "state": "DL",
        "city": "new city",
        "streetAddress": "my street"
      },
     "specialities": [
        {
          "_id": "577692f7",
          "name": "Football",
          "description": "game",
          "__v": 0
        }
      ]
    }

$ scope.test =數據; 我正在通過ng-repeat =“ mytest in test”在html中獲取數據,

mytest.address.city // this is working fine
mytest.specialities.name // not printing anything

我在訪問專業名稱時遇到問題,我認為這是因為專業是一個數組,但不知道如何獲取它。

您定義了一個內部只有一個數組的特殊對象

嘗試

mytest.specialities[0].name 

更新

另外,您可能要確保數組中至少有一個元素,否則可能會收到TypeError: Cannot read property 'name' of undefined

因此,代碼如下所示:

mytest.specialities.length > 0 ? mytest.specialities[0].name : '(some default value)';

是的, mytest.specialities是數組。 JSON有兩個可能的選項[] -數組, {} -對象。 在這種情況下,我們具有對象數組- [{/ *對象數據* /}],因此要首先獲取對象參數,就應像下面這樣轉到數組元素(示例在索引0上獲取第一個元素):

mytest.specialities[0].name 

第二個要素:

mytest.specialities[1].name 

每個示例:

<div  ng-repeat="special in mytest.specialities">
    <span>{{special.name}}</span>
</div>

當然,在此之前,將mytest設置為如下范圍:

$scope.mytest=mytest;//mytest is your data structure

假設會有很多專業,您應該使用ng-repeat來顯示所有專業。

<p ng-repeat="s in mytest.specialities"> {{s.name}} / {{s._id}} / {{s.description}} </p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM