更新ng-repeat时,html表不会更新

时间:2015-07-17 12:31:03

标签: javascript jquery html angularjs

我尝试通过在范围变量更新的表单中添加值来更新表,但是表仍然没有更新。 我的桌子

<tbody> 
    <tr ng-repeat="ct in city">
        <td>
            <center>[ {{ct.location.latitude}} , {{ct.location.longitude}} ]</center>
        </td>
        <td>
            {{ct.name}} 
        </td>

我更新列表的功能

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);
}

2 个答案:

答案 0 :(得分:0)

该表未更新,因为函数siteadd未在角度上下文中运行,因此它不会运行$digest周期来更新视图中的所有绑定。

要使其成为可能,您必须在函数中显式调用$digest周期,或者只将函数包装在$scope.$apply中。

代码:

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.
}

/ *****获取您的信息***** /

要更好地了解$watch, $digest and $apply,请参阅链接 &#34; http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/&#34;

答案 1 :(得分:0)

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>