Executing a function in JavaScript from an AngularJS Controller

Currently, I am in the process of transitioning my jQuery calls to AngularJS. Previously, I created a web page for zip code lookup using the ziplookup library, accessible through this link.

To implement this, I had to include the following script:

<script src="http://ziplookup.googlecode.com/git/public/ziplookup/zipLookup.min.js" type="text/javascript">
</script>

as well as the following jQuery code:

$(document).ready(function() {                                  // When the document loads,

            $.zipLookupSettings.libDirPath = 'ziplookup/'               // (Optionally) set the library folder path manually

            $('[name=zipcode]').blur(function(){                        // Set on blur
                $.zipLookup(                                            // Do a Zip code Lookup
                    $(this).val(),                                      // Zip code Field Value
                    function(cityName, stateName, stateShortName){      // If Successful,
                        $('input[name=city]').val(cityName);            // Set City name
                        $('input[name=state_short]').val(stateName);    // Set State abbreviation
                        $('input[name=state]').val(stateShortName);     // Set State name
                        $('.message').html("Found Zipcode");            // Add a message
                    },
                    function(errMsg){                                   // If Zip couldn't be found,
                        $('.message').html("Error: " + errMsg);         // Add an error message
                    });
            });
        });

Now, I am attempting to migrate this functionality to AngularJS. Instead of triggering the zipLookup function on blur event, I am now calling it upon button press with the same parameters. However, I am encountering errors such as ReferenceError: zipLookupSettings is not defined or ReferenceError: zipLookup is not defined.

$scope.zipeval = function(){
     //zipLookupSettings.libDirPath = 'ziplookup/';
    zipLookup(                                            // Do a Zip code Lookup
        11722,                                      // Zip code Field Value
        function(cityName, stateName, stateShortName){      // If Successful,
            $log.log(cityName + stateName + stateShortName);
            //$('input[name=city]').val(cityName);            // Set City name
            //$('input[name=state_short]').val(stateName);    // Set State abbreviation
            //$('input[name=state]').val(stateShortName);     // Set State name
            //$('.message').html("Found Zipcode");            // Add a message
        },
        function(errMsg){                                   // If Zip couldn't be found,
            $log.log("error");       // Add an error message
        });
};

I am seeking guidance on whether I need to create a directive for this situation.

Answer №1

You have identified this as a local function here.

Instead, refer to it as $.zipLookup.

Include a directive in your HTML.

<input name="zipcode" custDirective></input>

Within your directive's link function, you can attach to events such as 'blur' or 'click'. Utilize this to call $.zipLookup()

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

Place the element at the bottom of the row above

I'm utilizing Angular to retrieve a list of items from the server and exhibit them on the page using: <div class="col-sm-6 col-md-4" ng-repeat="activity in activities"> <img ng-src="[[ act.icon ]]" height="100" alt=""> <h3>[ ...

When running collection.find().toArray(callback) in node.js with mongodb, the result is coming back

When I run my code, mydocuments.find({}).toArray is returning empty. I have seen some solutions posted but they don't apply to my situation since I am using MongoClient.connect. Any help would be greatly appreciated. var MONGOHQ_URL="mongodb://harish ...

Challenges related to streaming processes and uploading to S3 cloud storage

Encountering difficulties with a zero byte stream. Currently, I am resizing an image and sending it as a stream to S3. Initially, when I connect the output to the response, it displays properly. // To retrieve the file remotely var request = http.get(&apo ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

The auto-play feature fails to function on iPhone devices when using Reactjs

I am currently working with Reactjs and Nextjs. I have a video on my website that is functioning properly on Android phones but not on iPhones. How can I resolve this issue? I have attempted the following code: <video loop autoplay='' muted> ...

Determine if a key begins with a specific string within an object and retrieve the corresponding value

If I have an object like this: let fruitSong = {'apple song':12, 'banana song': 24} Object.keys(fruitSong).forEach(e=>{ if(e.startsWith('apple')){ console.log(fruitSong[e]) } }) Is there a different meth ...

Tips for displaying external JavaScript code in an alert box:

Is there a way to display external JavaScript code in an alert or another location by accessing the variable value s_code? (function(){ var newscript = document.createElement('script'); newscript.type = 'text/javascript'; ...

Determine which file to load based on the size of the browser

I have a quick question regarding the correct syntax. I am trying to only load the jQuery file if the browser screen width is less than 1100px. <script type="text/javascript"> $(document).ready(function() { if ($(window).width() < 1100) { ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...

"Optimize Magellan Sidebar for Mobile Devices by Relocating it to the Bottom of the Page

After spending a week working with Foundation 5 framework, I'm curious if there is a straightforward way to make my magellan sidebar shift to the bottom of the page when viewed on mobile or tablets. <div data-magellan-expedition="fixed"> <di ...

Showing outcomes from various API requests

I have encountered an issue while making two API calls to a backend server and trying to display both responses in JSON format to the user. Strangely, alert 2 is showing as 'undefined' when I check the console, while alert 1 works perfectly fine. ...

An Ajax call is utilized to retain previous data

I'm currently facing a slight issue with my ajax request and I am still on the lookout for a solution. Here's what I'm trying to achieve: I have a basic search form where upon submission, the data is sent to a PHP file which returns the re ...

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

Guide on sending information using ajax using a button within a form

I've been working on creating a form that utilizes HTML5 validations and integrates Ajax to show the status of mail sending. However, I'm facing an issue where clicking the send button does not initiate the expected action. Form HTML: <div c ...