Wednesday, 12 April 2017

Angular JS ng-repeat doesn´t showing data correctly

I have a strange problem when using ng-repeat. Only as additional information, I am using ui-router as well.

I did a test with a simple markup that query some data in my local node server and shows with ng-repeat.

To make the test, I click a button to add a new row to server and next, I query the server again to get the new rows updated.

The problem is that the server return correctly all data with the new row added included, but ng-repeat is no showing the rows just added.

Here is more details of the problem.

Firstly, when the page is loaded I have

RowId
1
2

After I click the "Add and Refresh Row" button, I´d expect to have on the screen:

RowId
1
2
5

But I still have only:

RowId
1
2

In console,I checked the return data from my server after I add a row and the data returned is:

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

where item id=5 is the row just added, buit it doesn´t appears with ng-repeat.

What am I doing wrong?

//markup

<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">
      
  </div>
</div>  

//local server with server.js script at node.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);
});

//controller

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



via Luiz Alves

No comments:

Post a Comment