Guidelines for invoking a JavaScript function within an AngularJS controller

I have included a code snippet below.

sample.js


    (function() {
    /*global angular */
    'use strict';

    angular.module('myapp', ['spinner'])
       .controller('myCtrl', ['$scope', '$window', function ($scope, $window ) {

        $scope.methodname = function() {
            if(something){
                /* Doing some operations */
            }
        };
        
        // Define the callme javascript function here

        function callme(response){
            /* If I call like this, I'm getting an error in the console. */
        }

       }]);  /* Controller ends here */

       /* Creating a new anonymous function to perform some operations */
       (function () {
           'use strict';

           // Making use of controller parameters inside callme function
           code.util.myHTTP(url, function (response) {

               // Adding response to session storage
               callme(response);

           }, function () {
                   // Removing from session storage
           });

       })();
   }());

In this context, I am encountering difficulties calling the callme javascript function within the angular controller. The error message appearing in the console is:

Uncaught ReferenceError: callme is not defined

Is there a solution for this issue?

Edit:

The reason why I am defining the callme function within the controller is the necessity to utilize certain controller parameters inside that function.

I have already executed a function in my js file as shown below

.run(function($rootScope, $log, $window) {
});

How can I incorporate myCtrl within this setup?

Answer №1

A different approach

Initially, if you wish to utilize your `callme` controller function, it needs to be made accessible. As it stands now, it is still private. To make it public, simply append it to your controller's scope (similarly to how you did with `scope.methodname`) :

...
$scope.callme = function(){
...
}
..

Afterward, use this function within a module so that the controller can be accessed :

angular.module('amodule').run(['myCtrl ', function(myCtrl){
    myCtrl.callme();
}]);

An alternative method

The recommended approach is to employ a factory since you are looking to share a service :

angular.module('myapp').factory('myservice', function(){
    function callme(){
        // TODO : implement the service
    }
    return {
        callme:callme
    };
});

Subsequently, in a new module, invoke that method :

angular.module('amodule').run(['myservice ', function(myservice){
    myservice.callme();
}]);

If you intend to utilize that service outside of Angular (as per your requirement):

angular.injector(['myservice']).get('callme').call();

Edit: You can declare and inject the service or controller in a single run. It should function properly. Please bear in mind that injecting your controller within your module's `run` method indicates poor design. For sharing data/services, prefer using factories/services. With more code snippets, we would be able to assist you further.

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

Using JavaScript to implement word filtering in MongoDB

I'm currently in the process of creating a chatbot designed to filter questions, and I'm seeking guidance on how to refine the search in my MongoDb based on user input. At the moment, I have the following code: I aim to retrieve all the results ...

Evaluating Jasmine unit tests using promises with odata

I am new to working with Angular and unit testing in Angular. Our project involves using odata for performing CRUD actions on the database, so we have created a service for this purpose. Here is a snippet of our service code: function DatabaseService($htt ...

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

How to customize the appearance of a specific column in Ag-Grid using AngularJs

Is there a way to style a column in ag-grid using AngularJs? I am looking to make it resemble hyperlinks, possibly with different colors for visited and unvisited links. The specific style isn't crucial; I simply want to learn how to style a column. S ...

Troubleshooting Next.js Mobile Freeze Issue: Unresponsive Scroll After Page Transition

Encountered a strange bug while testing my Next.js + Bootstrap demo project on mobile view. When using the burger menu to navigate to a new page on a mobile phone, attempting to scroll down causes it to stick/freeze/hang inexplicably. Despite my efforts to ...

There is a lack of 'Access-Control-Allow-Origin' header, resulting in no access to the API

Having some trouble with the UK Parliament API, I keep encountering this error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not a ...

"Executing Javascript event onmouseUp without needing a click and hold

I've implemented an event listener for onMouseUp. I'm trying to distinguish between a quick click (short time duration) and an onMouseUp event that occurs after holding the mouse for more than one second OR with onMouseDown while moving the mous ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

Managing State in React using Maps

As someone who is new to coding, I am currently facing an issue and seeking help to resolve it. I am using axios to retrieve a JSON file and store it in a state utilizing Redux for form population. I am then utilizing .map() to break down the array and dis ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Utilizing Google Maps API version 3 to display various groups of markers

I am encountering an issue while trying to plot fixed markers and a user position marker on a Google Map. I want to use different images for these markers, but something strange is happening. When the page loads, all fixed markers show up correctly initial ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

Failed to execute test suite in React and Jest framework

While working on updates for our existing project, I encountered an error that is causing some of the tests to fail: FAIL src/components/changelog/__test__/ChangeLogOverView.test.tsx ● Test suite failed to run TypeError: Cannot create property & ...

My divs are multiplying twice as fast with every iteration of the Javascript For Loop

Recently, I developed a script that generates a series of fields based on a number provided by the user (k). Initially, I had a script that would create the correct number of fields. However, I decided to arrange them like vectors on the screen, so I made ...

Struggling with a minor glitch in a straightforward coin toss program written in JavaScript

I'm a newcomer to JavaScript programming and I am struggling with understanding how the execution flow is managed. I attempted to integrate an animation from "Animation.css" into a coin toss program, but encountered an issue. When trying to use JavaSc ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

org.openqa.selenium.WebDriverException: unexpected issue: Chrome failed to initiate: crashed.(chrome inaccessible)

Having issues running Java script (selenium framework) on Chrome. Tried various solutions but still facing problems: Unchecked run as admin Added arguments Snippet of the code: ChromeOptions options = new ChromeOptions(); //options.setExperimentalOption ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...