Daniel Williams Daniel Williams - 6 months ago 10
Javascript Question

Loading new JSON data into Angular on a click event

I have a PHP file that produces JSON data for my Angular array. Depending on the GET request, the data differs. The two URLs that produce different data include the string

data.php?c=1
or
data.php?c=2
.

On initial load I have
data.php?c=1
preloaded, but what I can't figure out is how I can dynamically load new data into the array and have it refresh on the page. In the example, I want to click the link that will trigger something to fetch the new data.

I'm really struggling with this. I'm not even sure my method is right int he first place, or if I should be reloading the page content with AJAX after fetching the new array.

<!DOCTYPE html>
<html ng-app="myApp">

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>

(function() {

var app = angular.module('myApp', []);

app.controller('FilesController', function ($scope, $http){
$scope.files = [];
$http.get('http://monstacdn.com/v2/data.php?c=1').success(function(data) {
$scope.files = data;
});
});
})();

</script>

</head>

<body>

<table ng-controller="FilesController">
<tr ng-repeat="file in files">
<td>{{ file.name }}</td>
<td>{{ file.size }}</td>
</tr>
</table>

<p><a href="#" onclick="doSomething('http://monstacdn.com/v2/data.php?c=2')">Change Data</a>

</body>
</html>

Answer

First of all you need to move ng-controller's directive inside your template, so you could react to click event inside this controller. The second - replace 'onclick' javascript event with 'ng-click' angular directive. So, your template's body will be:

<body ng-controller="FilesController">

<table>
    <tr ng-repeat="file in files">
        <td>{{ file.name }}</td>
        <td>{{ file.size }}</td>        
    </tr>
</table>

<p><a href="#" ng-click="doSomething('http://monstacdn.com/v2/data.php?c=2')">Change Data</a>

</body>

After that change your controller in this manner:

app.controller('FilesController', function ($scope, $http){
            $scope.files = [];

            $scope.doSomething = function(requestString){
              $http.get(requestString).success(function(data) {
                  $scope.files = data;
              });
            }

            $scope.doSomething('http://monstacdn.com/v2/data.php?c=1');
        });

So, when you will click on your link, it will call doSomething method, which is inside your controller's scope. And doSomething method will get data from your api.

Comments