Angular JS - How can I execute a method within a module?

Recently starting to work with Angular, I have been tasked with debugging my colleague's code. While going through the factory functions, I came across a scenario where I need to add a reset_All method that calls the reset function of all modules. How can I accomplish this?

.factory('MyCollection', function() {
    return {

        resetAll: function(projectId) {

          // call the reset function of SomeController

        }
    }
})

.controller('SomeController', function($scope, a) {


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

 }

Answer №1

If you are aiming to avoid tight coupling between modules, one approach is to trigger an event and handle it in the relevant controllers:

.factory('MyCollection', ['$rootScope', function($rootScope) {
    return {
        resetAll: function(projectId) {
            $rootScope.$broadcast('reset');
        }
    };
}]);

.controller('SomeController', ['$scope', 'a', function($scope, a) {
    $scope.reset = function() {
        // add your code here
    }; 

    $scope.$on('reset', function() {
        $scope.reset();
    });
}]);

For more information on Angular's events, check out Understanding Angular’s $scope and $rootScope event system $emit, $broadcast and $on

Answer №2

Make sure to rely on MyCollection for proper injection:

.controller('SomeController', [ '$scope', 'a', 'MyCollection',
    function ($scope, a, MyCollection) {


    $scope.reset = function(id) {
        MyCollection.resetAll(id)
    }

 }]);

Check out the official documentation for more information.

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 error encountered at line 8 in the file ui-bootstrap-tpls-0.14.3.min.js is: "Uncaught ReferenceError:

Everything was working perfectly in my application until I decided to install ui-bootstrap-tpls-0.14.3.min.js I added ui.bootstrap as a dependency like this: var app = angular.module("earnfitApp", ['ngRoute','ui.bootstrap']); I made ...

Error: Attempting to access the 'createClient' property of an undefined object - TypeError

Recently, I've been working on a project where I needed to create and store a session in redis. To achieve this, I referred to the API documentation provided by this GitHub repository https://github.com/tj/connect-redis. However, I encountered an iss ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

What is the best way to incorporate dynamic data from Firestore into a function using the `where()` method, while also utilizing the `snap.size` property to accurately count the total number of queries

I am facing an issue while trying to fetch data dynamically from firestore using a where() function. The specific error message I encountered is: TypeError: vaccines is not a function The user collection: [![enter image description here][1]][1] Here a ...

Use npm to import a module from the same index.js file that the current file is exporting from

Imagine a scenario where I have developed an npm package called @myscope/blurfl containing two classes: A, defined in A.js, and B, defined in B.js. Both classes are re-exported through blurfl/index.js: @myscope/ blurfl/ A.js B.js ...

Leveraging Axios for form data submission

Is it possible to serialize data from an HTML form element and then post the data using a Post request with Axios? Below is the event code triggered when a button click occurs to submit the post: function form_submission(e) { var data = document.getEleme ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

Position the <a> to the right side of the div

Is there a way to right-align the <a> element, which contains a Button with the text Push Me, within the <div> (<Paper>)? https://codesandbox.io/s/eager-noyce-j356qe This scenario is found in the demo.tsx file. Keep in mind that using ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Angular - Triggering actions with ng-hide and ng-show events

Is there a better solution for monitoring hide and show expressions across all elements in my app? I am aware that I can achieve this by wrapping the show directive with a function that simply returns the argument: <div ng-show="catchShow(myShowExpr = ...

Having trouble getting jsp to work with ajax

I'm currently learning web design through a co-op position at a company. Unfortunately, the department I am placed in lacks experts in web design. Nevertheless, I am determined to make it work. My current project involves creating a website that will ...

How can we combine refs in React to work together?

Let's consider this scenario: I need a user to pass a ref to a component, but I also have to access that same ref internally. import React, { useRef, forwardRef } from 'react'; import useId from 'hooks/useId'; interface Props ext ...

Protractor: Saving data locally with local storage - A step-by-step guide

I've come across several instances of retrieving previously saved information, but I haven't found any examples of retrieving stored values. ...

Angular's Checkbox Directive: A Flexible Solution for Checkbox Management

I am looking to create a directive for a checkbox input with a specific structure: <label for="sameID" class="style"> <input type="checkbox" id="sameID" name="name" /> <span>some text here</span> </label> I want to use t ...

Is it possible to watch AES encrypted token authenticated videos on iOS devices using Office 365?

I am currently using Azure media player to stream Office 365 videos, but I am encountering an issue where the videos do not play on iOS devices. I attempted to implement a solution from the provided link, but unfortunately it did not resolve the problem. ...

Angular 4 scripts fail to execute after switching views

I am facing an issue with my Angular 4 app. All scripts work fine when the page is loaded for the first time. However, if I navigate to a different component within the app and then return to the main page, the scripts stop working. The console log shows a ...

When using the same controller with two divs, the model does not appear to be updated

After assigning the same controller to two different divs, I noticed that the model being updated in one div is not reflected in the other. <body ng-app="myApp"> <div ng-controller="filterCtrl"> <p ng-bind="test" /> < ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

JavaScript/jQuery Progress Bar for Tracking File Downloads

I've been working on a project that involves downloading multiple files as a single zip file using the JSZip plugin. However, during the download process, the browser freezes up and I'd like to implement a progress bar to indicate how far along t ...