2016-08-23 60 views
0

我想基於ng-click來動態地訪問對象。我會用像這樣的按鈕來獲得很多的窗體。如何在angularjs中動態地訪問對象?

HTML

<button type="button" id="news" ng-click="home.addnew()">Update</button> 
<button type="button" id="allocation" ng-click="home.addnew()">Update</button> 
<button type="button" id="create" ng-click="home.addnew()">Update</button> 

我的對象

"home": { 
    "news": [{ 
     "type": "cd", 
     "title": "title1", 
    }], 
    "allocation": [{ 
     "type": "cd", 
     "title": "title2", 
    }], 
     "create": [{ 
     "type": "cd", 
     "title": "title3", 
    }] 
    .......etc 
} 

Angularjs控制器

$scope.home.addnew = function(){ 
    var type = $(event.target).attr("id"); 
     $scope.home.news.title; // Here how can I access that "news","allocation","create" Dynamically 
     $scope.home.type.title // I have tried like this 
} 

我收到錯誤

Cannot read property 'title ' of undefined 
+0

爲$ scope.home分配上述JSON對象? –

回答

4

您試圖訪問對象屬性而不是數組。

它應該是這樣的

$scope.home.addnew = function(){ 
    var type = $(event.target).attr("id"); 
    $scope.home[type][0].title; 
} 
0

你確定你已經連接家裏$範圍爲已經評論的用戶之一。 $ scope.home在開始處理之前需要存在。

0

您可以使用數組括號

var dynamicType ='news'; 
       var obj ={"home": { 
       "news": [{ 
       "type": "cd", 
       "title": "title1", 
       }], 
       "allocation": [{ 
       "type": "cd", 
       "title": "title2", 
       }], 
       "create": [{ 
       "type": "cd", 
       "title": "title3", 
       }] 
      }}; 
    console.log(obj.home[dynamicType][0].title);