1

Working on learning some Angular and I was wondering how I could replace this hardcoded JSON array to the JSON that is pulled with the http get. Here is the plunker im working on. At the top I do this to populate the dropdown i'm using:

angular.module('myapp', [])
  .controller('MainCtrl', function($scope, $http) {
    var records;
    $scope.selCountry = '';
    $scope.searchText = '';
    $http.get('http://www.w3schools.com/angular/customers.php').success(function(dt) {
      //window.alert(angular.toJson(dt));

      var countries = [];
      records = dt.records;
      dt.records.forEach(function(o) {
        var c = o.Country;
        if (countries.indexOf(c) == -1)
          countries.push(c);
      });
      $scope.countries = countries;
      $scope.total = countries.length;
    });

I don't know if this is where I would fill the array as well? Or is it even done like that (like I did above). Do I have to create the array for all objects or can I just access the incoming JSON. Thx.

Asta
  • 1,569
  • 13
  • 23
erp
  • 2,950
  • 9
  • 45
  • 90
  • 1
    You don't need to create an array if you don't want you can simply bind to the returned JSON object. Eg `$scope.customers = dt.records`. Generally speaking you want to assign your results when you get them so this is the correct place to do so. You may have more abstractions such as error handling etc but this is generally correct – Charleh Apr 20 '15 at 19:34
  • Angular will take care of updating the UI if you are binding anything to the customers variable in the scope (by dirty checking/whatever other methods the framework uses) – Charleh Apr 20 '15 at 19:37
  • Check out restangular: https://github.com/mgonto/restangular – alex Apr 20 '15 at 19:38
  • So since I already say `records = dt.records`, in the html can I just say `
  • `? because that didn't work when I tried it
  • – erp Apr 20 '15 at 19:43