Ad

Loading New Json Url On Button Click And Updating View In Angular

- 1 answer

Sorry if this question already exists but i could not find it.

I'm working on an Angular project, and I have loaded a external JSON file using http. This data is displayed using ngRepeat.

I would like to load the file again using different parameters when a button is clicked and update ngRepeat

JavaScript:

angular.module('App', [])
    .controller('ResultsCtrl', function($scope, $http) {
        $http.get(searchUrl).then(function(res){
            $scope.markersAll = res.data;     
        })
        .success(function(data, status, headers, config) {
            $scope.markersAll = res.data;
        })
        .error(function(data, status, headers, config) {
            // something went wrong
        });
});

HTML

<div ng-repeat="marker in markersAll">
    <h4>{{marker.org}}</h4>
</div>

<select id="Category_Selection">
    ...
</select>
<input type="button" onClick="searchLocations()" value="Search"/>

I have tried wrapping the JS in a function an calling it when the button is click, but that didn't work. How can I update $scope.MarkersAll using a new http GET request? Or is there a different way I should be loading this data?

Ad

Answer

edit: updated to use 'ng-click' instead of 'onClick'.

Btw, it's a good practice to use controllerAs syntax instead of binding directly to $scope.

angular
  .module('App', [])
  .controller('ResultsCtrl', function($scope, $http) {
    $scope.markersAll = []; //initialize to empty array so ng-repeat doesn't complain
    $scope.searchLocations = searchLocations;

    searchLocations(); //perform a search on load

    function searchLocations() {
      $http.get(searchUrl).then(function(res) {
        $scope.markersAll = res.data;
      });
    }
  });
<div ng-repeat="marker in markersAll">
  <h4>{{marker.org}}</h4>
</div>

<select id="Category_Selection">
  ...
</select>
<input type="button" ng-click="searchLocations()" value="Search" />

Ad
source: stackoverflow.com
Ad