2015-11-24 34 views
0

对不起,有一个非常愚蠢的问题,但我刚开始使用AngularJS和OnsenUI。初始化AngularJS服务 - 文档加载工厂

我有一个服务从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> 

Can an an ybody帮助我如何在页面加载完所有内容后立即初始化控制器。对不起,如果这是一个愚蠢的问题,但我真的很挣扎。非常感谢你的帮助。

回答

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请求。

+0

谢谢。我有一个错误:**期望一个赋值或函数调用,而是在这一行看到一个表达式**:$ update.requestValues;不幸的是,当页面加载后,它不会加载内容,必须点击两次才能看到内容。 – qqruza

+0

对不起,忘记把它们称为函数'()'。 Se更新了答案 – sjokkogutten