I'm trying to update a $scope variable onClick that populates a table from a local JSON file. So far my code is
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$scope.update = function () {
// Load JSON data to $scope
$http({
method: 'get',
url: '/JSON/Info.json'
}).then(function (response) {
console.log(response, 'res');
$scope.friendz = response.data[1];
},function (error){
console.log(error, 'can not get data.');
});
}
});
<div ng-controller="myCtrl" class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<button class="dropdown-item" ng-click="update()">Action</button>
</div>
<div ng-controller="myCtrl">
<table border="1">
<tr>
<th>Name</th>
<th>Fax</th>
<th>Phone</th>
<th>Address</th>
<th>Attention</th>
<th>Submission</th>
</tr>
<tr>
<td ng-bind="friendz.Payee.Name"></td>
<td ng-bind="friendz.Payee.Fax"></td>
<td ng-bind="friendz.Payee.Phone"></td>
<td ng-bind="friendz.Payee.Address"></td>
<td ng-bind="friendz.Payee.Attention"></td>
<td ng-bind="friendz.Payee.SubmissionDate"></td>
</tr>
</table>
</div>
When I click my update button in the dropdown menu, I see the response is logged in the console, but the table fails to update onClick. Is there a function that I need to call to update the page in an asynchronous fashion when I click my button? When I use the http get function outside of my scope.update function, it works fine on page load.
1 Answer 1
You're creating two separate instances of your controller, since you have ng-controller="myCtrl" twice in the template.
So he controller handling the click is not the same one that holds the data displayed by the table. And their scope are not the same either: each controller instance has its own scope.