当前位置: 代码迷 >> JavaScript >> 更新ng-repeat时html表未更新
  详细解决方案

更新ng-repeat时html表未更新

热度:115   发布时间:2023-06-12 14:23:14.0

我尝试通过范围变量被更新但表格保持未更新的形式添加值来更新表格。 我的桌子

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

该表未更新,因为函数siteadd不在angular上下文中运行,因此该表未运行$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请参阅链接“ ”

 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> 

  相关解决方案