Sharing methods between controllers in AngularJS

After coming across this insightful article on Angular validation, I decided to implement it in my project. The validation is functioning perfectly, but I am struggling to access methods in other controllers upon successful form validation. Despite trying various approaches, I am unable to see the methods in the $scope object.

<!DOCTYPE html>
<html>
  <head>
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89ebe6e6fdfafdfbe8f9a4eafafac9baa7b9a7b9">[email protected]</a>" 
      data-semver="3.0.0" 
      rel="stylesheet" 
      href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e81889a838e9dc1859cafdec1dfc1d7">[email protected]</a>" 
      data-semver="1.0.8" 
      src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="rcSubmit.js"></script>
    <script src="loginController.js"></script>
    <script src="loginApp.js"></script>
  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="col-xs-12 col-sm-6 col-sm-offset-3">
          <h1>Simple Login Form</h1>
          <form name="loginForm" novalidate 
            ng-app="LoginApp" ng-controller="LoginController" 
            rc-submit="login()">
            <div class="form-group"
              ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.username)}">
             <input class="form-control" name="username" type="text" 
              placeholder="Username" required ng-model="session.username" />
             <span class="help-block" 
              ng-show="loginForm.username.$error.required">Required</span>
            </div>
            <div class="form-group"
              ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.password)}">
              <input class="form-control" name="password" type="password" 
                placeholder="Password" required ng-model="session.password" />
              <span class="help-block" 
                ng-show="loginForm.password.$error.required">Required</span>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary pull-right" 
                value="Login" title="Login">
                <span>Login</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

I am reaching out for assistance to identify the missing element that will enable me to achieve my objective. For reference, I have shared a link to a plunkr.

Answer №1

To effectively handle this, utilizing an angular service is the best approach. Consider the following:

app.factory('svc', function () {
    var msg="original...";
    return {
        setMessage: function(x) {
            msg=x;
        },
        getMessage: function() {
            return msg;
        }
    };
});

By doing this, you can utilize the functions within svc in any controller where you inject svc:

app.controller("ctrl1",function($scope,svc,$timeout){
  $scope.someText=svc.getMessage();
  $scope.$watch("someText",function(v){
    svc.setMessage(v);
  });
});

app.controller("ctrl2",function($scope,svc){
  $scope.msg=svc.getMessage();
  $scope.$watch(svc.getMessage,function(v){
    $scope.msg=v;
  });
});

Check out this demonstration plunk (I didn't address the plunk you shared initially due to excessive noise).

UPDATE

Executing the service method and form validation are not directly connected, as shown in this plunk.

UPDATE

If you wish to utilize the services or controllers from one app in another, simply reference the dependencies in your primary app and use the services defined in the main app within your secondary app. If your main app is named demoApp1, you can create another app called demoApp2, reference demoApp1 in demoApp2, and use any services defined in demoApp1 within demoApp2. Refer to the updated plunk to see an example of what you're inquiring about.

Answer №2

The most efficient method for facilitating communication between the two controllers is by utilizing events.

For more information, you can refer to the Scope Documentation.

Be sure to explore the use of $on, $broadcast, and $emit.

Typically, the function angular.element(catapp).scope() is intended for situations outside of angular controllers, such as within jquery events.

In your scenario, you would create an event in controller 1 like this:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

Then, in the second controller, you simply need to do:

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Consider adding the firstApp module as a dependency to the secondApp when defining the angular.module. This will enable effective communication between the two applications.

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

Vue (Gridsome) App encountering 'Cannot POST /' error due to Netlify Forms blocking redirect functionality

Currently, I am in the process of developing my personal website using Gridsome. My goal is to incorporate a newsletter signup form through Netlify Forms without redirecting the user upon clicking 'Submit'. To achieve this, I utilize @submit.prev ...

Enter your password using the text input field on Internet Explorer 8

I'm currently developing a website and facing an issue with the password input field: When clicking on it in browsers like IE9, Chrome, and Mozilla, the text changes to allow entry of the password. However, in IE8, clicking on the input field leaves ...

My HTML gets rearranged by browsers, causing a change in appearance

UPDATE: I have discovered that the issue lies with Internet Explorer which alters the class attribute of an HTML element from: "<img class="blah".." to "<img class=blah..". This inconsistency only occurs in IE for me. It does not affect other attr ...

Only one JSON file is handled at a time, no duplicates are made

We start by utilizing the powerful D3 JavaScript library for initializing data documents, followed by creating a custom JavaScript script to handle data processing. An excerpt from the customized JavaScript script appears as follows: drawLegend(); ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

CKeditor with Kcfinder

Although I've seen similar topics, none seem to match my exact situation. I recently added CKEditor to my website and wanted to integrate KCFinder as the file manager. Following the instructions on KCFinder's website, I copied the necessary file ...

When ng-app has a value other than an empty string, the angular directives will fail to function as expected

I am just beginning to explore AngularJs and I'm puzzled by a strange behavior in my code. When the value for ng-app is left as an empty string, the Angular directives work fine. However, when the value is not an empty string, the directives do not se ...

Check the validity of multiple selection groups using JavaScript

Here is the link to my JS Fiddle: http://jsfiddle.net/m4tyC/ I am working with multiple select tags and need to validate them upon submission. For example, at least one of size1, color1, or Qty1 must be selected in the first group. If one item is selected ...

Can you explain the functionality of the return false statement within the validate plugin's submitHandler

While exploring the validator plugin examples, I stumbled upon a code snippet online: $('#testimonials-form').validate({ rules: { "t-title": { required: true, minlength: 5 }, "t-text": { ...

Having trouble accessing the href attribute after clicking on an <a> tag with JavaScript

My issue lies in retrieving the href attribute of <a> tags when there is another element nested inside them: Here's the code snippet: const $elems = document.querySelectorAll('.content-container a') var elems = Array.from($elems) e ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Having trouble with expressJs router.post() not functioning properly with multiple middleware, resulting in an [object Undefined] error

I have been working on developing a REST API for my users, utilizing express-validator for validation before adding the user to the database. However, I encountered an issue while chaining my middleware in the router.py file which resulted in the error Err ...

Download the browser version of UglifyJS 2 now

Is there a way to download the browser version of UglifyJS 2 without having to build it myself? I'm running into issues with the manual installation. I used npm to install uglify-js, but I can't seem to find where to execute the uglifyjs --self ...

Displaying API logs on an Html console

function updateData(e) { const animeName = e.target.value; const apiUrl = `https://nyaaapi.herokuapp.com/nyaa/anime?query=${animeName}`; fetch(apiUrl) .then((res) => res.json()) .then(displayAnimeData); } const inputField = document.getEl ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

Updating the status of the checkbox on a specific row using Typescript in AngularJS

My goal is to toggle the checkbox between checked and unchecked when clicking on any part of the row. Additionally, I want to change the color of the selected rows. Below is my current implementation: player.component.html: <!-- Displaying players in ...

The customer opts to store all images indefinitely into the data stream

I have set up a node server that captures images from a webcam at regular intervals and sends them to the client using the Delivery.js node module. Upon monitoring the browser resources in Chrome development tools, it appears that each image sent is being ...

Issue: tanstack_react_query's useQuery function is not recognized

Error: (0 , tanstack_react_query__WEBPACK_IMPORTED_MODULE_3_.useQuery) is not a function While implementing data fetching in my Next.js project using @tanstack/react-query, I encountered the above error message. Below is the code snippet where the issue ...

ng-options encounters duplicate data when using group by in Internet Explorer

The dropdown menu that lists states works fine in Google Chrome, but duplicates groups in Internet Explorer. In Chrome, there are 2 groups, but in IE there are 4. How can I fix this issue in IE as well? Thank you. Here is the code snippet: <!DOCTYPE h ...

Injecting Variables Into User-Defined Button

Presenting a custom button with the following code snippet: export default function CustomButton(isValid: any, email: any) { return ( <Button type="submit" disabled={!isValid || !email} style={{ ...