简体   繁体   中英

AngularJs extracting values from JSON Object and attaching to $scope

I am receiving the following JSON data object

{
  "ip": "**Removed**",
  "country_code": "GB",
  "country_name": "United Kingdom",
  "region_code": "ENG",
  "region_name": "England",
  "city": "Plymouth",
  "zip_code": "PL6",
  "time_zone": "Europe/London",
  "latitude": 50.442,
  "longitude": -4.0828,
  "metro_code": 0
}

How do I extract the first two values and attach them to the $scope so that they can be shown in the template when received. ?

Assuming that you're getting it via http request your call would be like this:

  $http.get("./getData.php").success(function(data) {
      $scope.data = {};                 
      $scope.data["ip"] = data["ip"];
      $scope.data["country_code"] = data["country_code"];
  }

You can set this whole object to a property on the scope in your controller:

$scope.jsonObject = jsonObject;

Then in your template, just access it like:

<span>{{jsonObject.country_code}}</span>

If I understood correctly, first store that JSON into one varaible

Var jsonData = { "ip": " Removed ", "country_code": "GB", "country_name": "United Kingdom", "region_code": "ENG", "region_name": "England", "city": "Plymouth", "zip_code": "PL6", "time_zone": "Europe/London", "latitude": 50.442, "longitude": -4.0828, "metro_code": 0 }

$scope.firstTwoValues = jsonData.ip+jsonData.country_cody;

For dynamic names u can use smth like this:

someDataService.get()
   .then(function(res) {
     var keys = Object.keys(res.data).splice(1,2);
     angular.forEach(keys, function(key){
        $scope[key] = res.data[key];
     });
     return $q.when();
   }

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