AngularJS在$ resouce.query之后不更新视图

时间:2017-05-19 14:06:15

标签: angularjs

我正在使用$ resource.query从后端获取数据。它正在发挥作用。但在得到回复后,视图不会改变。当它不在函数内时它会起作用。

这是我的服务

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

这是我的控制器

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

这是我的观点

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

3 个答案:

答案 0 :(得分:1)

假设调用getData(),您将结果附加到未定义的变量teste,而不是$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);
    });
}
}]);

答案 1 :(得分:1)

承诺的结果存储在结果变量的“数据”中,因此请将视图更改为

<tr ng-repeat="d in data.data">

或您的控制器

$scope.data = data.data;

答案 2 :(得分:0)

你的第二个非工作版本等于$scope.getData到一个不返回任何内容的函数。

相关问题