SQLite does not work global


#1

Hello I wonder if you guys can help me with this problem.
To start the js my application is in app.js and controllers.js created a database for test and it worked but only within the function that declared

app.js
`angular.module(‘starter’, [‘ionic’, ‘starter.controllers’, ‘ngCordova’])

.run(function($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);

}
if (window.StatusBar) {
  // org.apache.cordova.statusbar required
  StatusBar.styleDefault();
}

});
})`

controllers.js

`angular.module(‘starter.controllers’, [])
.controller(‘AppCtrl’, function($scope, $ionicModal, $timeout) {

//I want to use the database here
})

.controller(‘PlaylistCtrl’, function($scope, $stateParams) {

//I want to use the database here
})

.controller(‘SorteiosCtrl’, function($scope, $stateParams) {

//I want to use the database here

})

.controller(‘MeusJogosCtrl’, function($scope, $cordovaSQLite) {
//Here the database works fine but I want to be able usalo in all my controls

var db = $cordovaSQLite.openDB({name: “mega_sort.db”});
$cordovaSQLite.execute(db, ‘CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT)’);

$scope.statusMessage = ‘’;
//console.log(db);
$scope.save = function(newMessage) {
// execute INSERT statement with parameter
$cordovaSQLite.execute(db, ‘INSERT INTO messages (message) VALUES (?)’, [newMessage]).then(function(result) {
$scope.statusMessage = “Message saved successful, cheers!”;
}, function(error) {
$scope.statusMessage = "Error on saving: " + error.message;
})

}

$scope.load = function() {

    // Execute SELECT statement to load message from database.
    $cordovaSQLite.execute(db, 'SELECT * FROM messages ORDER BY id DESC').then(function(res) {

                if (res.rows.length > 0) {

                    $scope.newMessage = res.rows.item(0).message;
                      var msg = '';
                    for (var i = 0; i < res.rows.length; i++) {
                      msg += res.rows.item(i).message;
                    };

                    $scope.statusMessage = msg;
                }
            },
            function(error) {
                $scope.statusMessage = "Error on loading: " + error.message;
            }
        );
}

})`

You guys have any idea how to make the global database on controllers.js file so that I can insert and query data in all my controller


#2

Don’t put the database abstract layer in a controller, but in a service/factory. The service/facory will hold the instance to the database. A service/factory is an singleton object.


#3

Thanks for your help, you would have some example to show me?