I am creating a single functionality : On a click of a button using AngularJS, i make an ajax call to some JSON data from the server.
Without the button functionality the following code is working:
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="customersController">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
function customersController($scope,$http) {
$http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}
</script>
</body>
</html>
But when i add a button click functionality the data doesnt get displayed on click of that button
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="customersController">
<button ng-click="getData()">Get Data</button>
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
function customersController($scope, $http) {
$scope.getData()= $http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function (response) { $scope.names = response; });
}
</script>
</body>
</html>
Please Help!
</div>
You've got two little errors here.
You can't assign something to the return value of a function. Look at what you're doing on this line: $scope.getData()= $http......
. This is telling JS to run $scope.getData
as a function, but you can't use an equal sign right afterwards to assign something to that return value. $scope.getData
is also likely undefined, which is just going to be a script error.
The second thing you're doing wrong is that the code you wrote, assuming you fixed #1 and made it $scope.getData = $http....
instead, is that you're immediately running that $http.get
code, and then assigning the return to $scope.getData
. What you really want to do is create a reusable function. You do this as follows:
$scope.getData = function () {
// function instructions
}
Fix those two problems, and you should be golden.