Using a promise inside an Angular custom filter

I am attempting to implement a filter that will provide either a success or error response from the ret() function. The current code is returning {}, which I believe is its promise.

.filter('postcode', ['$cordovaSQLite', '$q',
function($cordovaSQLite, $q) {
    return function(PostCodeID) {
        function ret() {
            var def = $q.defer();
            ionic.Platform.ready(function() {
                if (window.cordova) {
                    var db = $cordovaSQLite.openDB({
                        name: "msddocapp.db"
                    });
                } else {
                    var db = window.openDatabase("msddocapp.db", "1", "ES Database", 5 * 1024 * 1024);
                }
                var query = "select * from PostCode where ServerID = ?";
                $cordovaSQLite.execute(db, query, [PostCodeID]).then(function(s) {
                    if (s.rows.length > 0) {
                        def.resolve(s.rows.item(0).Title);
                    }
                }, function(e) {
                    console.log(e);
                    def.reject(PostCodeID);
                })
            });
            return def.promise;
        }
        return ret().then(function(s) {
            return s;
        }, function(e) {
            return e;
        });
    }
}]);

This filter is specifically for a single ng-repeat, so perhaps I could attach a function directly to ng-repeat like:

HTML

{{getPostName(item.id)}}

Angular.js

function getPostName(id) {
    return post[id].name;
}

Answer №1

After reviewing your comment

I have identified the PostCode in the database and need to retrieve its value to replace the ID, for example if id = 1 then the corresponding value is 00-000

To achieve this, you must utilize a directive to make the database call and manipulate the DOM accordingly.

http://www.sitepoint.com/practical-guide-angularjs-directives/

Directive:

angular.directive('postcode', ['$cordovaSQLite', '$q', function($cordovaSQLite, $q){
    return {
        template: '{{getPostName(item.id)}}',
        link: function(scope, elem, attrs) {
            scope.getPostName = function(PostCodeID) {
                var def = $q.defer();
                ionic.Platform.ready(function() {
                    if (window.cordova) {
                        var db = $cordovaSQLite.openDB({
                            name: "msddocapp.db"
                        });
                    } else {
                        var db = window.openDatabase("msddocapp.db", "1", "ES Database", 5 * 1024 * 1024);
                    }
                    var query = "select * from PostCode where ServerID = ?";
                    $cordovaSQLite.execute(db, query, [PostCodeID]).then(function(s) {
                        if (s.rows.length > 0) {
                            def.resolve(s.rows.item(0).Title);
                        }
                    }, function(e) {
                        console.log(e);
                        def.reject(PostCodeID);
                    })
                });
                return def.promise.then(function(s) {
                    return s;
                }, function(e) {
                    return e;
                });
            };
        }
    };
}]);

HTML:

<div data-postcode></div>

EDIT:

As this directive shares the scope with its parent, simply adjust the template to use the variable being passed in, i in this case:

HTML

<tr ng-repeat="i in data.contacts">
    <td>
        <div data-postcode></div>
    </td>
</tr>

Directive

template: '{{getPostName(i.id)}}'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to run JavaScript within PHP, an Uncaught SyntaxError is encountered

When I run this code without PHP, it works perfectly. <?php $activeStatus = "$getuser[active]"; if($activeStatus == 1) { echo '<script type="text/javascript">'; echo ' $(document).ready(function () { v ...

Navigate to a different subdomain and place a cookie on the newly redirected subdomain

The version of Express is 4.x NodeJS is running on version 12.x At a.example.com, I have a listener for the GET method that redirects to b.example.com and sets a cookie on b.example.com. app.get('/foo', (req, res) => { res.cookie(' ...

Filtering data with Django Filter: Dynamically setting ChoiceFilter options based on user request

I am trying to use django-filter and require a ChoiceFilter with choices that are determined based on the request I receive. While going through the documentation for ChoiceFilter, I noticed it states: This filter matches values in its choices argument. Th ...

What sets apart the $ and $() functions in jQuery?

After reviewing the jQuery API, I noticed that $() represents a collection of matched elements. However, I am curious about the significance of $. An example from the imagesLoaded library is provided below. if ( $ ) { $.fn.imagesLoaded = function( opt ...

Executing a click on a checkbox element in Python with Selenium

Background: Currently, I am in the process of developing a Python script that will automatically download listings from a specific website. I have successfully programmed the script to navigate the webpage, search for keywords, click on the search button, ...

Acquiring backend information to display in front-end using ReactJS

I receive data from the backend to present it in the following font: componentDidMount() { const response = this.props.store.privateImputationData; console.log(response); } When I check the console, it shows null. However, if I use a setTimeout, it w ...

What is the best way to retrieve a specific property or attribute of a specific div element after obtaining it from e.target.parentNode?

e.target.parentNode will return this element. <div class="quantity"> <span class="glyphicon glyphicon-minus-sign"></span> <span class="product_Count"> 4 </span> <spa ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

Use a service method to update the selected scope variable

Imagine a scenario where 'User' represents a service and 'User.get' is a method that performs a request. <button class="btn" ng-click="User.get(users,'id,uname,email,pw')"> <p>{{users}}</p> How can I utiliz ...

Executing Javascript without invoking the default behavior

Recently, I've been delving into the world of JavaScript and experimenting with the prevent default command for ajax pagination. Here's the code I've come up with: http://jsfiddle.net/6pqfH/2/ $('.pagination').click(function(e){ ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

When attempting to update a task with the Microsoft Graph API, the server returned a 400 error code

Attempting to update a Task using the Graph API from an angular2 typescript app. Here is an example of my request - Request URL:https://graph.microsoft.com/beta/tasks/_1EKXXuN1UGInJ9yVHAjIpYAKuC2 Request Method:PATCH Request Body: { "createdBy":"f16 ...

Personal Information Management

After making a request for stormpath user custom data, I used the following code: res.render('home', { title: 'home', user: req.user.customData, }); Instead of receiving a JSON object of custom data as expected, a URL ('') ...

Collaborating with multiple forms and files in PHP using jQuery and AJAX operations

Need help with the title for this question. There are two input fields and buttons in index.php <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <input type="text" class="for ...

Discover the country's three-letter code with the power of HTML and Javascript!

I am in search of a way to determine the location of a user based on the country they are browsing from. I want to achieve this using HTML and Javascript. While researching on stackoverflow, I came across various suggestions to use different API's for ...

Issue encountered while trying to implement a recursive function for mapping through nested elements was not producing the

I am currently working on recursively mapping through an array of nested objects, where each object can potentially contain the same type of objects nested within them. For example: type TOption = { id: string; name: string; options?: TOption; } con ...

Having issues with the functionality of the Previous/Next button in my table

I am facing a challenge with my table as I am trying to include previous/next button for users to navigate through it. However, the interaction doesn't seem to be functioning properly, and I suspect that I need to establish a connection between the bu ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...

Issue with mapStateToProps not reflecting changes in props after localStorage modification

Currently, I am working on a redux application that involves authentication. My main concern right now is ensuring that the user remains logged in whenever they interact with the app. Below is a snippet from the bottom of my App.jsx file: function mapStat ...