JonathanMRibeiro JonathanMRibeiro -4 years ago 66
AngularJS Question

AngularJS does not update view after $resouce.query

I'm fetching data from backend using $resource.query. It's working. But after I got the response, the view doesn't change. It works when it's not inside a function.

this is my service

app.factory('myService', function ($q, $resource, $http) {
var service = {};
service .pesquisar = function (param1, param2) {
return $q(function (resolve, reject) {
$resource(urlWebService + '/API/', null).query({
param1: param1,
param2: param2
}, function (dados) {
resolve(dados);
}, function (erro) {
reject(erro);
});
});
};
return service ;
});


this is my controller

app.controller('myController', ['$scope', '$resource', 'myService',
function ($scope, $resource, myService) {

//this call update the view
myService.fetchData('1234', '111111')
.then(function (data) {
$scope.data = data
})
.catch(function (erro) {
console.log(erro);
});

//this is called in a button click and doesn't change the view
$scope.getData = function () {
myService.fetchData('1234', '111111')
.then(function (data) {
$scope.data = data
})
.catch(function (erro) {
console.log(erro);
});
}
}]);


and this is my view

<table>
<thead>
<tr>
<th>Field</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="d in data">
<td>{{d.field}}</td>
</tr>
</tbody>
</table>

Answer Source

Assuming getData() is invoked, you're using appending the result to a variable teste that is not defined, instead of the $scope

$scope.getData = function () {
  myService.fetchData('1234', '111111')
    .then(function (data) {
      //teste.data = data 
        $scope.data = data; //will bind the result to the view
    })
    .catch(function (erro) {
      console.log(erro);
    });
}
}]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download