【问题标题】:Angular JS ng-repeat doesn´t showing data correctlyAngular JS ng-repeat 不能正确显示数据
【发布时间】:2017-09-09 00:00:09
【问题描述】:

我在使用 ng-repeat 时遇到了一个奇怪的问题。 仅作为附加信息,我也在使用 ui-router。

我使用一个简单的标记进行了测试,该标记在我的本地节点服务器中查询一些数据并使用 ng-repeat 显示。

为了进行测试,我单击一个按钮向服务器添加新行,然后再次查询服务器以更新新行。

问题是服务器正确返回了包含新添加行的所有数据,但 ng-repeat 没有显示刚刚添加的行。

这里是问题的更多细节。

首先,当页面加载时,我有

RowId
1
2

单击“添加和刷新行”按钮后,我希望屏幕上有:

RowId
1
2
5

但我仍然只有:

RowId
1
2

在控制台中,我在添加一行后检查了服务器返回的数据,返回的数据是:

{id:1,name:'John Doe'},
{id:2,name:'Mary Doe'}
{id:5,name:'teste'}

其中 item id=5 是刚刚添加的行,但它不会出现在 ng-repeat 中。

我做错了什么?

//标记

<div  ng-controller="configClinicaClinicaCtrl"> 
  <a class="btn btn-sm btn-success" ng-click="saveClinica()">Add and Refresh Row</a>
  <div>RowId</div>
  <div ng-repeat="row in dados track by $index">
      {{row.id}}
  </div>
</div>  

//在 node.js 上带有 server.js 脚本的本地服务器

var clinicas=[
{id:1,name:'John Doe'},
{id:2,name:'Mary Doe'}
];

//get clinicas
app.get('/clinicas', function(req, res) {
  res.json(clinicas);
});

//insert clinica
app.post('/clinicas', function(req, res) {
  clinicas.push(req.body);
  res.json(true);
});

//控制器

angular.module("clinang").controller('configClinicaClinicaCtrl',['$scope','$http', '$state', function($scope,$http, $state) {
      $scope.dados={};
      $scope.clinica={};
      var refreshData=function(){
        $http.get('/clinicas').then(function(response){
            $scope.dados=response.data;
        }, function(error){
          console.log(error)
        });
      }
      refreshData();


     $scope.saveClinica=function(){
        $scope.clinica.id=5; 
        $scope.clinica.nome='teste';
        var clinica=$scope.clinica;
        $http.post('/clinicas',{clinica}).then(function(response){
            refreshData();
        }, function(error){
          console.log(error)
        })
      }
}]);

【问题讨论】:

    标签: angularjs node.js


    【解决方案1】:

    每当您在 AngularJS 之外进行某种形式的操作时,例如进行 API 调用,您都需要让 AngularJS 知道自己进行更新。试试这个,

     var refreshData=function(){
            $http.get('/clinicas').then(function(response){
                $scope.dados=response.data;
                 $scope.$apply();
            }, function(error){
              console.log(error)
            });
      }
    

    【讨论】:

    • 感谢您的回复。我刚刚做了,但问题仍然存在。 ng-repeat 中的 RowId 不会随着添加的新行而更新
    • @LuizAlves 这不应该是一个数组 $scope.dados={};?
    • 是的,我有teamviewer。你想要吗?
    • 如何将 id 和 pw 发送给您?
    猜你喜欢
    • 2017-04-15
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多