I am a new AngularJS learner.
My code is calling a JSON file and displays the output. However, I want the call to change the JSON call based on change in certain variable (i.e. KeyWord).
Here is the HTML part:
<body ng-controller="AppController">
<button type="button" class="btn btn-danger" ng-click="ChangeKW()">
Click to Change KeyWord
</button>
<div ng-controller="customersController as custCont" ng-model="keyWord">
KeyWord:{{ keyWord }} ==== iter:{{ iter }}
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
</body>
And here goes the Controller part:
var app = angular.module('App', []);
app.controller('AppController', function($scope, $window) {
$scope.keyWord = 3;
$scope.iter = 1;
$scope.ChangeKW = function() {
if ( $scope.keyWord === 3 )
$scope.keyWord = 1;
else
$scope.keyWord = $scope.keyWord + 1;
}
});
app.controller("customersController", function($scope, $http) {
$scope.iter = $scope.iter + 1;
$http({
url: 'test' + $scope.keyWord + '.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response) {
$scope.names = response;
}).error(function(error) {
$scope.names = [{
"Name": "Errrrrrr"
}];
});
});
I want the program to load respective JSON file text1.txt, text2.txt or text3.txt based on value of KeyWord variable, which can be changed by clicking on the red button. I have defined mg-model="KeyWord" in HTML, which changes the value of {{ KeyWord }} in the output but it doesn't send refresh JSON call/output. The initial file loaded is tex3.txt (all three files can be distinguished from 1st record).
The Plunker can be found here: Plunker.
you probably need:
$scope.$watch('keyWord',function()
{
//$http call here
}
);
the ‘$watch‘ will make the $http call automatically, each time $scope.keyWord changes.