javascript - Angular js 两种方式数据绑定(bind)仅适用于 apply

标签 javascript angularjs asynchronous 2-way-object-databinding dexie

我的 Angular 应用程序有/需要两种方式的数据绑定(bind)。

我使用注入(inject)到 Controller 中的 Angular 服务从 indexedDB 获取数据。

我需要在从数据库获取数据后更新 View 。

var app = angular.module("app",["ngRoute"]);

app.config(['$routeProvider',function($routeProvider) {
    //removed extra routes for simplicity
    $routeProvider.when('/grouped',{
        templateUrl: 'template/grouped.html',
        }).otherwise({
        redirectTo: '/grouped'
    });
}]);

同一文件中的 Controller

 app.controller("AppController",function ($scope,dexiedb) {
    $scope.datais={};
    $scope.dataisdata={};
    $scope.alldata = {};

    var scholar = {};

    var _db;
    window.initial = 0;
    var callback_alldata = function(err,data){
      if(!err){
      /* If I put apply it works*/
      // $scope.$apply(function() {
        $scope.alldata = data;
            // });
      }
    console.log('in callback_alldata ',err,data);
    };

    var init = function() {
      console.log('hi in init');
      dexiedb.getdata(callback_alldata);
      console.log($scope);
    };
  init(); 
 });

从数据库获取数据的服务

app.service('dexiedb',function(){

  var createdData = {};
  var _db = null;

  var service = {};
  //Initialization code which makes connection
  service.init = function(){

  _db = new Dexie('puppets');
  _db.version(1).stores({
        snips: "++id, text",
        parent: "++id, title, timeStamp"
    });

   _db.open().then(function(){
      service.createdata();
      console.log('service.init then called');
     }).catch(function(e){
      console.log('error opening',e);
            });
  };
  //The actual place where data is fetched and returned
   service.createdata = function(callback){
      console.log('createdata');
        var alldata = [];
      _db.transaction('rw',_db.parent, _db.snips, function(){

        _db.parent.each(function(par){
          var r = {'parent':par,'snips':[]};
          _db.snips.where('URL').equals(par.URL).each(function(snip){
              r.snips.push(snip);
          });
          alldata.push(r);
          // console.log(alldata);
        }).then(function(){
          createdData = alldata;
          console.log('createdata',createdData);
          return callback(null,createdData);
          // return createdData;
        });
      });
    };
//The method which is called in the controller
service.getdata = function(callback){
  // console.log(createdData);
  if (Object.keys(createdData).length==0) {
    console.log('createdData was empty');
    return service.createdata(callback);
  } else return callback(null,createdData);
}

service.init();

return service;

 });

我知道,如果更新变量的位置不在 Angular 范围内,则应使用 $scope.apply 。在回调中不会出现 Angular 范围吗?

数据已获取并记录在控制台中,但直到我单击另一条路线然后再次返回时,它才会显示在 View 中。

我对promise/callback的理解还不够扎实,问题是由于回调处理不当造成的吗?

最佳答案

问题是 Angular 不知道对 $scope 所做的更改(即 $scope.alldata = data;)。

对 Controller 中的 $scope 所做的更改将立即更新,但您的代码位于回调内。 Angular 在回调被触发之前到达了 Controller 的末尾,因此它错过了摘要周期。它无法知道您的回调已被调用。

当您在回调中更新 $scope 时,不会触发新的摘要周期。

dexiedb 似乎未使用 $http,因此在这种情况下您需要使用 $scope.$apply。您可以看到angular's implementation of $http其中包括$apply

关于javascript - Angular js 两种方式数据绑定(bind)仅适用于 apply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887761/

相关文章:

javascript - 如何获取 x 和 y 值来检测 html5 Canvas 中两个图像之间的碰撞?

javascript - 如何从 event.target 获取 react 元素

javascript - 如何在 Angularjs 中使用超时功能切换 div 层?

angularjs - 如何仅将某些域的 header 添加到 $http

javascript - 从第一个下拉列表中选择 "NA"值不应禁用第二个下拉列表中的 "NA"值

javascript - 控制 javascript 异步流的速率(在循环中)

javascript - 使用 Google Charts 实时变化的点位图

javascript - 如何在不使用内联 SVG 的情况下重叠两个 SVG 向量?

javascript - Sentry.io 管理异步 Node.js 服务器上的错误范围/上下文

c# - 当异步代码试图在一个已经在执行的线程上恢复时会发生什么?