Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller.

Here is an example of the external.js file:

...
...
function fun() {
  ...
  ...
}
...
...

The controller in question is called acccountController.js:

myApp.controller('AddAccountController', function ($scope, AddAccountLoginServices, $location, localStorageService, $compile, toaster) {
   ....
   ....

   $scope.getLoginForm = function(siteId, name) { 
            ...
            ...
            fun(); // Calling a function from the external.js file
   });

   ...
   ...

});

I have imported external.js before the acccountController.js, but the function is not being called without any console errors. How can I achieve this successfully? Thank you in advance.

Answer №1

Correction: My initial answer was incorrect, I apologize for the mistake. The example provided below is the correct solution.

Your external file should be set up like this:

var doSomething = (function () {
  "use strict";
   return {
      test: (function () {
        return 'test';
      }()),
      test2: (function () {
        return console.log('test 2');
      })
   };
}());

In your controller, you can call your script functions as follows:

console.log(doSomething.test);

or

doSomething.test2();

I also gained some insights from this, thank you for the lesson!

Answer №2

In a post by @nilsK, the concept of a self-executing function is explained. This function is then referenced through the window object. Here's an example -

(function functionName(){
    Do Something Here...
})();

Following that,

window.functionName();

If you are working with AngularJS,

$window.functionName();

Answer №3

I encountered a similar scenario where I didn't need to use a self-invoking function. By simply adding the external JavaScript file to the HTML, everything worked smoothly.

Answer №4

Have you located the function $scope.getLoginForm()? It seems like you may have forgotten to call it, which means that fun() is also not being called and you won't see any results. Make sure to include a call to $scope.getLoginForm(). You can do this in two ways: In your HTML:

<button ng-click="getLoginForm()"></button>
Or in your Javascript: $scope.getLoginForm() Best of luck!

Answer №5

To make the function accessible globally, you should instantiate it as a global instance.

Simply insert this line of code at the end of your file:

var myFunction = new functionName();

Now, in your controller, you can call any method from this file using myFunction.methodName.

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

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

Steps to resolve the Error: $injector:unpr Unknown Provider in AngularJS when establishing a connection to a Laravel database

Recently, I've delved into learning AngularJS and attempting to create a basic webpage that connects AngularJS with a backend Laravel database by following some tutorials. However, I keep encountering an error message stating: Error: $injector:unpr ...

Ways to showcase the content of a page once the controller variables have been set

As someone who is just starting out with AngularJS and web development, I am curious to know if there is a way to delay the display of a page until after all of the controller's $scope variables have been initialized. Most of my $scope variables are c ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

When a new component is loaded, React Martial UI component may face issues due to overwriting or

Currently, we are working on a vast web application that utilizes jquery and bootstrap. Our current task involves transitioning this extensive app to React with Material UI, piece by piece. As we progress towards transforming it into a React app, everythin ...

Instantly display selected image

I have encountered some challenges with my previous question on Stack Overflow as I couldn't find a suitable solution. Therefore, I decided to explore an alternative method for uploading images. My current goal is to upload an image immediately after ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

Troubleshooting: Navbar dropdown menu in AngularJS gets hidden within UI layout

After spending some time trying to understand why the NavBar drop-down is getting overlapped inside the ui-layout, I realize that I must be overlooking some basic steps. This issue seems so simple, yet it is eluding me. To see the details of the problem, ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

Angular directive: inability to pass ng-repeat item through isolate scope

I am currently working on a directive that has an isolate scope. The template of the directive includes an ng-repeat on an element, along with the following code snippet: ng-click="selection(item)" Within the directive's scope definition, I have spe ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

Leveraging jQuery to delay the processing of AJAX requests

Managing a list of 15+ ajax requests that need to be executed in a specific sequence can be challenging. Each ajax call must wait for the previous one to finish before proceeding. This issue is compounded by the fact that the callback function for each aja ...

Developing a dynamic horizontal bar chart in d3 using a multidimensional array or nested JSON dataset

I am in the process of creating a straightforward d3 bar chart () by utilizing this specific nested json file. { "clustername": "cluster1", "children": [ { "neighborhoodname": "Shaw", "children": [ { "totpop2000": "1005", "children": [ ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Pop-up confirmation dialog in JQuery following an AJAX request

In order to validate on the server side whether a person with a specific registration number already exists in the database, I have implemented a process. If the person is found registered, the program flow continues as usual. However, if the number is not ...

Imposing the situation

In my current class, I have a private property and a public method for access: Person = function () { this.Name = "asd"; var _public = new Object(); _public.Name = function (value) { if (value == undefined) { //Get return ...

When working with an outdated package, you may encounter a situation where babelHelpers is not

My current focus is on a vuetify v1.5 project. Unfortunately, one of the dependency packages (d3-flextree) is causing an issue with the 'babelHelpers is not defined' error. The solution I came across suggests using transform-runtime instead of th ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...