简体   繁体   English

AngularJS不更新$ scope

[英]Angularjs not update $scope

I'm having trouble with my controller not updating Gui $scope . 我的控制器无法更新Gui $scope遇到了麻烦。 After some research, I found out that you can use $timeout . 经过研究,我发现可以使用$timeout

The service takes different time on different units and I do not want set like 5000 timeout because the app feels slow. 该服务在不同的设备上花费的时间不同,我不希望设置为5000超时,因为该应用感觉很慢。 Is there any other way to do this? 还有其他方法吗?

.service('RowService', function ($q) {

var rows = undefined;
this.getrows = function (id) {
  var local = new PouchDB('db');
  var deferred = $q.defer();
  //      var rows = [];
  local.query(function (doc, emit) {
    emit(doc.type);
  }, { key: 'row_detail' }).then(function (result) {
    var rows = [];
    for (i = 0; i < result.rows.length; i++) {
      local.get(result.rows[i].id).then(function (response) {
        if (response.orderid == orderId) {
          rows.push(response);
        }
        deferred.resolve(rows);
      })
    }
  }).catch(function (err) {
    // handle any errors
  });

  rows = deferred.promise;

  return $q.when(rows);
}

})


RowService.getrows($stateParams.id).then(function (data) {

    // Not working example
    $scope.rows = data;
    // Working example

  $timeout(function () {
    $scope.rows = data;
  }, 5000)

}

$scope.$apply() can sometimes lead to problems, but $timeout can be called without delay: $ scope。$ apply()有时可能会导致问题,但是$ timeout可以立即被调用:

.service('RowService', function ($q) {

var rows = undefined;
this.getrows = function (id) {
  var local = new PouchDB('db');
  var deferred = $q.defer();
  //      var rows = [];
  local.query(function (doc, emit) {
    emit(doc.type);
  }, { key: 'row_detail' }).then(function (result) {
    var rows = [];
    for (i = 0; i < result.rows.length; i++) {
      local.get(result.rows[i].id).then(function (response) {
        if (response.orderid == orderId) {
          rows.push(response);
        }
        deferred.resolve(rows);
      })
    }
  }).catch(function (err) {
    // handle any errors
  });

  rows = deferred.promise;

  return $q.when(rows);
}

})


RowService.getrows($stateParams.id).then(function (data) {

    // Not working example
    $scope.rows = data;
    // Working example

  $timeout(function () {
    $scope.rows = data;
  })

}

Then don't provide timeout value it will work and the function will be called after all the functions have been executed. 然后,不要提供超时值,它会起作用,并且在所有函数执行完后将调用该函数。 moreover you are suing promise in your service so you don't need a timeout value. 此外,您在服务中要求诺言,因此您不需要超时值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM