对于一个非常愚蠢的问题感到抱歉,但我刚开始使用AngularJS和OnsenUI。
我有一项服务从SQLite获取数据:
module.factory('$update', function () {
var update = {};
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM event_updates', [], function (tx, results) {
var rows = results.rows;
update.items = [];
if (!rows.length) {} else {
for (var index = 0; index < rows.length; index++) {
update.items.push({
"title": rows.item(index).title,
"date": rows.item(index).date,
"desc": rows.item(index).desc
});
}
}
}, function (error) {
console.log(error);
});
});
return update;
});
正在使用数据的控制器:
module.controller('UpdatesController', function ($scope, $update) {
$scope.items = $update.items;
});
我的页面一加载,内容就不会显示,我需要点击两次才能使用下面的代码调用页面来查看内容:
<ons-list ng-controller="UpdatesController">
<ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in items" ng-click="showUpdate($index)">
<div class="list-item-left">
</div>
<div class="list-item-right">
<div class="list-item-content">
<div class="name">{{item.title}}</div> <span class="desc">{{item.desc}}</span>
</div>
</div>
</ons-list-item>
</ons-list>
任何人都可以帮助我们如何在页面加载所有内容后立即初始化控制器。对不起,如果这是一个愚蠢的问题,但我真的很挣扎。非常感谢你的帮助。
答案 0 :(得分:1)
您可以将请求的结果存储在工厂中,然后检索它们。
module.factory('$update', function () {
var update = {};
var requestValues = function(){ // store the results of the request in 'update'
// Your db.transaction function here
}
var getUpdates = function(){ // retrieve the values from 'update'
return update;
}
return{
requestValues : requestValues,
getUpdates : getUpdates
}
});
然后在你的控制器中:
module.controller('UpdatesController', function ($scope, $update) {
$update.requestValues();
$scope.items = $update.getUpdates();
});
然后,您可以从解决方案中的任何位置获取值(使用$update.getUpdates
),而无需进行额外的http请求。