我的 Angular 应用程序有/需要两种方式的数据绑定。
我使用注入控制器的角度服务从 indexedDB 获取数据。
从 db 获取后,我需要更新视图。
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'
});
}]);
同一文件中的控制器
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();
});
从 db 获取数据的服务
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;
});
我知道$scope.apply
如果要更新变量的位置不在角度范围内,则应该使用它。在回调中不会出现角度范围吗?
数据已获取并登录到控制台,但在我单击另一条路线然后再次返回之前,它不会显示在视图中。
我对 promises/callback 的理解还不牢固,问题是由于回调处理不当造成的吗?