Executing a function from a JavaScript file in an Angular application

I've got a file called test.js with the following code:

function test(str) {
    return 'Hello, ' + str + '!'
}

My goal is to utilize the test method in my Angular controller:

angular.module('testModule')
.controller('testController', ['$scope', function($scope){
    console.log(test('John'))
}

This will result in Hello, John!

I attempted the following:

<div ng-app="testModule" ng-controller="testController">
    <script type="text/javascript">
        function test(str) {
            return 'Hello, ' + str + '!'
        }
    </script>
</div>

It worked as expected, returning Hello, John!. However, trying to reference the method from my other .js files leads to

ReferenceError: ____ is not defined
.

  1. How can I access methods from other .js files within my Angular controller?
  2. What is the recommended approach for invoking these methods? (e.g. Do I need to migrate the code from all my .js files into Angular's model or controller?)

Answer №1

To ensure the singleton pattern is maintained, it is advisable to create a service specifically for handling singleton objects. In a production environment, real objects can be passed to this service, while in testing scenarios, mock objects can be utilized instead. For a practical example, refer to http://jsfiddle.net/mendesjuan/E9bU5/235/

While Angular provides mechanisms for managing dependencies, opting to directly access global variables like jQuery or toaster from controllers is also a viable option.

angular.
module('testModule', []).
 controller('testController', ['$scope','test', function ($scope, test) {
   $scope.callTest = function(msg) {
     return test(msg);
   };
 }]).
factory('test', [function() {
   return function(msg) {
     return 'Hello, ' + str + '!';
   } 
}]);

// An illustration of using a global variable
window.myTest = function() {
    return "I'm in";
};


angular.
module('testModule', []).
 controller('testController', ['$scope','test', function ($scope, test) {
   // Testing becomes easier with services that can be mocked
   $scope.callTest = function(msg) {
     return test(msg);
   };
   // However, accessing globals can complicate testing process
   $scope.myTest = function() {
      return myTest();
   }
 }]).  
factory('test', ['$window', function(str) {
   return function(str) {
       return 'Hello, ' + str + '!'
   }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testModule" ng-controller="testController">
    <!-- Displaying results -->
     <h1>{{ callTest('You') }}</h1>
     <h1>{{ callTest('Me') }}</h1>
     <h1>{{ myTest() }}</h1>
</div>

Answer №2

To begin, you will need to create a service within your module. There are various methods for creating a service, each tailored to different requirements and preferences. Let the experts debate on the best approach.

angular.module("myModule")
    .factory("myService", function() {
        return {
            sayHello: function(name) { 'Hello, ' + name + '!';}
        }
    });

Next, you can inject this service into your controller:

angular.module('myModule')
    .controller('myController', ['$scope', 'myService', function($scope, myService){
        console.log(myService.sayHello('Alice'));
    });

It is important to note that Angular's injection process allows flexibility in defining the order of creation. You can define the controller before the service and Angular will still handle the injection seamlessly.

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

Anticipated input should be in the format of '_item_ in _collection_[ track by _id_]' but instead received

Having trouble with ng-repeat in AngularJS, only showing first element and getting a console error: Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '”pm'. angular.module('DataCabinet') .c ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...

One-liner for converting an array into an object

Is there a more concise method to convert all array indices and values into an object than the following: arr = ["one","two","three"]; var rv = {}; for (var i = 0; i < arr.length; i++) rv[i] = arr[i]; I understand that you can iterate through the ...

Is it possible to set specific points within a Points object in THREE.js to be transparent or invisible?

I am working with a Three.js Points object that holds information for displaying multiple points in 3D space. I am looking for a way to dynamically hide certain points, but I am uncertain of the process. The PointsMaterial used has xyz data stored in poin ...

Has the rotation of the model been altered?

Is there a way to detect if the rotation of a model has changed? I've attempted: var oldRotate = this._target.quaternion; console.log('works returns vector3 quaternion: ', oldRotate); var newRotate = oldRotate; if (oldRotate != ...

Show information when table is clicked

I currently have a 9 x 9 table with unique content in each cell. Is there a way to enable the following functionality: Upon clicking on the text within a specific cell, all related content would be displayed right below that same cell? For instance, if ...

Guide to displaying an email template on a webpage

I am facing a challenge with rendering an email template on a web page. The email template comes with its own CSS, for example: <style> body{ font-size : 20px; } </style> However, when I attempt to display the email template on my webpage, ...

Iterate over the keys within a JSON array that begin with a certain key name

Is there a more efficient way to dynamically loop through keys in a JSON array starting with 'option' and either loop through them all or set a maximum limit? Currently, I am using the following approach: $.each(shopifyProductJSON.variants, fun ...

Ways to verify the timeframe between two specific dates

Having two distinctive arrays: accomodation: [ { id: 1, name: "Senator Hotel Fnideq", address: "Route de Ceuta, 93100 Fnidek, Morocco", checkin: "September 1", fullCheckinDate: "2021-09-01", ...

I'm in the process of designing a Todo list platform, but I've hit a roadblock trying to figure out the best way to showcase and delete tasks

Having some trouble with creating an li element even after following the necessary steps. Any guidance and explanation would be greatly appreciated. Thank you Managing HTML and CSS is fine, but when it comes to JavaScript, I always seem to struggle. I und ...

React Prop Local Modal Redux

Just diving into the world of React and Redux, and I'm a bit lost on how to effectively utilize both local properties and redux properties simultaneously. After trying different approaches without success, I'm reaching out for guidance. My goal i ...

Encountering a problem while attempting to implement server side rendering with ReactJS.Net in conjunction with EPiServer

I am currently working on implementing server-side rendering with ReactJS.Net within an EPiServer project. To achieve this, I am utilizing the ReactJS.Net Html extension provided for rendering. However, upon running my site, I encountered an error. The ...

React: The error message "p is not defined" is showing up in the component file due to the no-undef

In my React application, I am looking to display a list of menu items from an array and show the detailed description of each item upon clicking. The array of menu items is stored in a separate file called dishes.js. The menu items are rendered using a Me ...

Access HTML content including styles using Angular

I have created an Angular application and I am looking to extract the html of a template from a large component, including the styles applied to the classes used. Can anyone advise on how to achieve this in Angular? Currently, I am attempting to use the fo ...

Enhancing a simple HTML 5 project by integrating JS dependencies with minimal recompilation or processing

If I have a collection of .html, .css, and .js files that I am serving as static resources via a web server. There are countless JS packages available on NPM repository. I am curious about the process of packaging these libraries (downloading and extra ...

Using AngularJS to dynamically update an array of objects in response to a selection change

I am facing a challenge with two dynamic object arrays: one for colors and one for buses. The main objective is to assign a color to each bus. I have used ng-repeat to create selects for each color, and employed ng-change to call the updatebus function, pa ...

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

Utilizing Media Queries with Dynamic Vue Properties

On one of my website pages, I always have a Div element with a Background Image that changes based on Media Queries (for example, I fetch a smaller resolution from my CDN on mobile phones). However, since I retrieve the Image URL on Page Load, I need to s ...

Exploring the functionality of filtering cards using a search box in Bootstrap 5 and JavaScript

https://i.sstatic.net/VlD20.png I tried to bring the medicine I searched for to the top by clicking on the search button, but unfortunately it did not work. Can someone help me with writing the JavaScript code for this? <form class="form-inline ...