Question

I have problem with the Scope of JS functions and/or Angularjs promise and $q. I looked up some examples but I did not get it at all.

In my app I have some data saved in indexeddb of my browser. In Frontend there is an input field with autocomplete function. The value of the input field goes to my angularjs Controller and calls a function. The function should return the found values. The logic of finding values from indexeddb is working fine.

The problem is that I return my array before the values are pushed into the array. So I am not sure if I need to change some stuff in JavaScript scope or to use Angularjs stuff.

Here is my Controller:

 var AutocompleteController = function($scope, $http, $q) {

 $scope.getCodeFromDB = function(val) {
        var codes = [];
            var openDbRequest = indexedDB.open('testDb', 1);

            openDbRequest.onsuccess = function (e) {
                var db = e.target.result;
                var transaction = db.transaction("codeobjekt");

                transaction.objectStore("codeobjekt")
                    .openCursor(IDBKeyRange.bound(val, val + '\uffff'))
                    .onsuccess = function (e) {
                    var cursor = e.target.result;
                    if (cursor) {
                        codes.push(cursor.value.code); //gets filled
                        console.log(cursor.value.code);
                        cursor.continue();
                    }
                };
            };

        console.log(codes); //is empty
        return codes;
    };
};

Thanks in advance.

Was it helpful?

Solution

in your code you try to use an array filled after the return.

Try using the $q service provides by angular like that.

var AutocompleteController = function($scope, $http, $q) {

    $scope.getCodeFromDB = function(val) {
        var def= $q.defer(),
            codes = [],
        openDbRequest = indexedDB.open('testDb', 1);

        openDbRequest.onsuccess = function (e) {
        var db = e.target.result;
            var transaction = db.transaction("codeobjekt");

            transaction.objectStore("codeobjekt")
                .openCursor(IDBKeyRange.bound(val, val + '\uffff'))
                .onsuccess = function (e) {
                var cursor = e.target.result;
                if (cursor) {
                    codes.push(cursor.value.code); //gets filled
                    console.log(cursor.value.code);
                    cursor.continue();
                }
                else {
                    //cursor end
                    def.resolve(codes);
                }

            };
        };

        return def.promise;
    };
};

And the usage

//usage

$scope.getCodeFromDB("value")
.then(function(codes) {
    //codes filled
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top