简体   繁体   中英

How to read json in angularjs?

I have the following json:

{
"a1": [
"b1","b2"
],
"a2": [
"c1","c2","c3"
]
}

In my controller i get json with the following code:

$.getJSON('tk.json', function(data) {
$scope.$apply(function(){
$scope.modelData = data;
});
});

I watch a variable and when it changes, i want to get the specific list from json. For example:

$scope
.$watch(
'value1',
function() {
if ($scope.value1 != null)           
{                                                                         
var tempValue = $scope.value1;
$scope.data = $scope.modelData.temValue;           
console.log($scope.data);//undefined
}
});

If value is a1 i want the list=["b1","b2"]. With the following $scope.data = $scope.modelData.temValue; i get value undefined for $scop.data.

How can i read json in order to find the right list? Thank you

Since your $scope.modelData is an object, you must access its properties in two ways:

  • Directly: $scope.modelData.a1
  • By String: $scope.modelData['a1']

So, as you have a variable tempData , and it's a String, you must use:

$scope.data = $scope.modelData[tempValue];

By doing $scope.data = $scope.modelData.tempValue; as you were, it will try to find a property named tempValue inside the $scope.modelData variable, and that property doesn't exist.

That's why your console is logging undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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