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

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

Error: Your Discord bot is unable to send a message as it is empty. Please check Discord

I have been developing a Discord Bot to verify Roblox accounts. Although my script is prepared and the command "-verify" can be executed, an error arises: (node:22872) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use `n ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Tips for toggling the visibility of a flexbox-styled popup using jQuery

I am trying to implement a popup on my website and I want to use flexbox styling for it. I have the necessary scss mixins for flexbox properties, however, I encountered an issue. The problem arises when I try to hide the popup using display: none, as the ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel: public class BusinessModel { public string BlobName { get; set; } public string NewName { get; set; } } In my MVC Ajax Controller, I have an action called DoBusiness: [HttpPost] public A ...

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

Peruse a spreadsheet for relevant information

I am currently facing an issue with a search bar that I implemented to filter through a table. However, for some reason, the filtering function does not seem to work on the tbody section of the table. The content in the tbody is generated dynamically usi ...

Sending various values to a JavaScript function

I am working with a function that looks like this: //Function Call with Single Parameter responses(baseURL); //Function Definition function responses(baseURL) { $.ajax({ url: baseURL, type: "get", cache: false, header ...

Error: Vue is unable to access the property '_modulesNamespaceMap' because it is undefined

I've been working on a simple web app to enhance my testing skills in Vue using Vue Test Utils and Jest. However, I encountered an error related to Vue while trying to console log and check if AddDialog is present in my Home file. The error message I ...

Angular UI Router allows for the resolution of data before a state

When working on my angular sample route, I attempted to achieve the following: (function(angular){ 'use strict'; angular .module('appRouter',['ui.router']) .controller('routerCtrl',function( ...

Issues with the functionality of AngularJS routing system

angular.module('Stations', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/documents/:stationId', { templateUrl: '/Scripts/Modules/checklist/views/index.html', ...

Encountering issues with importing a module from a .ts file

Although I have experience building reactJS projects in the past, this time I decided to use Node for a specific task that required running a command from the command line. However, I am currently facing difficulties with importing functions from other fil ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

Omit node_modules from typescript compilation using gulp-typescript

Having trouble running a gulp task to compile my typescript due to dependency-related errors. /content/node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'. /content/node_modules/@angular/core/src/facade/l ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...

Tips for building and implementing Angular URL Parameters for URLs in the form: "component/#/?id=..."

I am currently facing a situation where I have an application with an existing user base. I am looking to avoid disrupting their current links for a smoother transition. However, the previous links are in this format: (server)/viewer/#/?id=12. Please see t ...

Having trouble with jQuery on my webpage

Looking for assistance with a technical issue I'm facing... I am currently working with AngularJS and have integrated jQuery into my project. However, I've encountered an issue where the jQuery code is not functioning as expected on the HTML pag ...

Delaying loops with JQuery Ajax

I am attempting to implement a delay in my AJAX data processing so that the loop runs a bit slower. Here's the code I'm working with: $(document).ready(function (){ $('#button').click(function(){ $('#hide').show ...