I try to update the table by adding values through the form the scope variable gets updated but by table remains non updated. My table
<tbody>
<tr ng-repeat="ct in city">
<td>
<center>[ {{ct.location.latitude}} , {{ct.location.longitude}} ]</center>
</td>
<td>
{{ct.name}}
</td>
my function to update list
window.siteadd = function(){
var citlat = document.getElementById("citylat").value;
var citlan = document.getElementById("citylon").value;
var citname = document.getElementById("cityname").value;
var citstat = document.getElementById("citynostation").value;
var citytemp = {
location:{
latitude: citlat,
longitude: citlan
},
name: citname,
}
console.log("temp", citytemp);
$scope.city.push(citytemp);
console.log("tempadded", $scope.city);
}
The table is not getting updated because the function siteadd
is not running in context of angular and so a $digest
cycle is not run by it for updating all the bindings in the view.
To make it possibe you have to call a $digest
cycle explicitly in your function or just wrap the function inside $scope.$apply
.
For your code:
window.siteadd = function(){
var citlat = document.getElementById("citylat").value;
var citlan = document.getElementById("citylon").value;
var citname = document.getElementById("cityname").value;
var citstat = document.getElementById("citynostation").value;
var citytemp = {
location:{
latitude: citlat,
longitude: citlan
},
name: citname,
}
console.log("temp", citytemp);
$scope.city.push(citytemp);
console.log("tempadded", $scope.city);
$scope.$digest(); //just add this line and it will work.
}
/***** For your Information *****/
To better understand $watch, $digest and $apply
please refer to the link " http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/ "
var app=angular.module("app",[]) app.controller("itemController",function($scope){ $scope.citytemp = { location:{ latitude: null, longitude: null }, name: null } $scope.city=[]; $scope.city.push($scope.citytemp); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> </head> <body ng-app="app"> <div ng-controller="itemController"> City Name: <input type='text' ng-model='citytemp.name'><br> Latitude: <input type='text' ng-model='citytemp.location.latitude'><br> Longitude: <input type='text' ng-model='citytemp.location.longitude'><br> <table> <tbody> <tr ng-repeat="ct in city"> <td> City Name: {{ct.name}} <br> Location : [ {{ct.location.latitude}} ,{{ct.location.longitude}} ] </td> <td> </td> </tr> </tbody> </table> </div> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.