【问题标题】:Select websql Data using Angular JS使用 Angular JS 选择 websql 数据
【发布时间】:2014-12-13 00:17:21
【问题描述】:

我正在尝试找出最好的方法来做到这一点。我正在尝试将数据插入 WebSQL 表,然后从表中选择数据并使用 ng-repeat 显示在屏幕上。我正在使用这个 Angular WebSQL 模块https://github.com/paulocaldeira17/angular-websql#select-all。 到目前为止,我可以获取远程数据并将它们插入本地数据库。当我尝试调用插入数据时, $scope.localproducts 显示一个空数组 - console.log( $scope.localproducts) 显示一个空数组。 我将 localproducts 范围用于我的 ng-repeat。

我无法从 Factory 的 selectAllData 函数将 ProductsFactory.localproducts 数组返回到我的控制器。

当点击我页面上的按钮时,它会调用我控制器中的 insertData 函数。

我在这里做错了什么?我对 Angular 很陌生,所以如果有人可以帮助我改进以下代码或建议是否有更好的方法来做到这一点,我将非常感激。

.controller('DownloadProductsCtrl', ['$scope','ProductsFactory', function ($scope, ProductsFactory){
    $scope.products = ProductsFactory.products;
    $scope.localproducts = ProductsFactory.localproducts;

    $scope.insertData = function(){
        ProductsFactory.getRemoteData().then(function(results){
            $scope.localproducts = ProductsFactory.localproducts;
            console.log( $scope.localproducts); //This shows an empty array
        });
    }; }])

.factory('ProductsFactory', ['$webSql', function($webSql){
    db = $webSql.openDatabase('myappdb', '1.0', 'Test DB', 2 * 1024 * 1024);
    ProductsFactory = {};
    ProductsFactory.products = [];
    ProductsFactory.localproducts = [];

    ProductsFactory.getRemoteData = function () {
        return $http.get('./products/list.json')
        .success(function (data) {
            ProductsFactory.products = data;
            ProductsFactory.insertData(data);
        })
        .error(function () {
            console.error('Error');
        });
    };

    ProductsFactory.insertData = function (data){
        angular.forEach(data, function(value, key) {
            db.insert('products', value).then(function(results) {
                <!-- In here I like to count the total inserted items and display it on the page, but not sure sure how to send it to a scope in my controller -->
            });     
        });
        ProductsFactory.selectAllData();
    };

    ProductsFactory.selectAllData = function(){

        db.selectAll("products").then(function(results) {
          for(var i=0; i < results.rows.length; i++){
             ProductsFactory.localproducts.push(results.rows.item(i)); //This added data to the array successfully.
          }
          console.log(ProductsFactory.localproducts); //This shows an empty array
        });
    };

    return ProductsFactory;

}]);

【问题讨论】:

  • 没有人对此有答案吗??

标签: javascript angularjs web-sql angular-promise


【解决方案1】:

尝试将此资源作为起点。

https://gist.github.com/jgoux/10738978

https://github.com/paulocaldeira17/angular-websql/blob/master/angular-websql.js

第一个非常基础,更容易理解。第二个涉及更多。

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2016-07-03
    • 2015-04-09
    • 2015-11-11
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2016-09-05
    • 2016-04-07
    相关资源
    最近更新 更多