Using $rootScope in AngularJS: A Beginner's Guide

Passing three instances of $rootScope from the process controller to the Rating controller allows me to enable and disable buttons based on the status of $rootScope. The functionality for edit and view is functioning properly, but when $rootScope === 'NewPrt', I want to enable the submit button after the user has answered all questions.

Here is the code I have tried so far:

HTML

<button type="submit" class="btn btn-default" ng-disabled="disabledDraft"  ng-click="savePRTDraft()" ng-show="showSaveDraftBtn">Save
        as Draft</button>
    <button type="submit" class="btn btn-primary"
        ng-disabled="disableSubmitButton" ng-click="submitClicked()">Submit</button>

ProcessCtrl.js

$scope.gotoQstnPage = function(isNew) {
        var qrtUrl = "/createRtgQstnAir/"+$scope.processDTO.processKey + "/"+isNew;
        $rootScope.status = 'NewPrt';
        $location.path(qrtUrl);
    }

$scope.editProcessRating = function(prcsSessionKey) {
            var prtUrl = "/getProcessRating/"+prcsSessionKey;
            $rootScope.status = 'edit';
            $location.path(prtUrl);

        }

        $scope.viewProcessRating = function(prcsSessionKey) {
          var prtUrl = "/getProcessRating/"+prcsSessionKey;
          $rootScope.status = 'view';
          $location.path(prtUrl);
        }

RatingCtrl.js

if(j > $scope.questionnaire.length){
              if($rootScope.status ==='edit') {
                $scope.disableSubmitButton = false;
                $scope.disabledDraft = false;
                $scope.showBusDecDropDown = true;
              }

 $scope.disabledDraft = function(){
        if($rootScope.status === 'view') {
          return true;
        }
        else {
          return false;
        }
      }
      if ($rootScope.status === "NewPrt" ) {
        $scope.disabledDraft = false;
      }

Answer №1

If you want to avoid using $rootScope, you can try the following approach:

var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="Controller">
    <form name="myForm">
        <input name="myText" type="text" ng-model="mytext" required />
        <button ng-disabled="myForm.$invalid">Save</button>
    </form>
</div>

Answer №2

To activate the submit button, ensure that both conditions are met:

if ($rootScope ==='edit' || $rootScope ==='NewPrt') {
    $scope.allowSubmit = true;
}

Answer №3

In order to utilize $rootScope, make sure to inject it into every controller where you intend to access config and run functions.

Here's an example:

var app = angular.module('app');
app.config(function($rootScope){
  $rootScope.name = "Greetings Earthlings"
});

app.controller('home',function($scope,$rootScope){
$scope.name = $rootScope.name;
alert($scope.name) 
})

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

Angular and Meteor light up the screen when the page loads

I encountered an issue with my angular-meteor project where the data would flicker every time a state using the campaigns subscription was loaded. The data would appear, disappear for a moment, and then reappear half a second later. To fix this, I include ...

JavaScript regex for UK cell phone numbers

I am currently implementing the following: phone_number.match(/^((\+44\s?|0)7([45789]\d{2}|624)\s?\d{3}\s?\d{3})$/); In most cases, the above code works well. Valid formats include: 07714000000 +447714000000 Howev ...

Transmitting a notification from the controller to the view

I am working on an asp.net mvc4 application and I want to include a JavaScript alert in the view. Here is my code snippet for the view: @{ try { string str = ViewData["Alert"].ToString(); <script>alert(@ ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Ways to reach the factory through the controller

My factory is structured like this: rasm.factory('serviceUrl',[function(){ function serviceUrl(){ this.p = location.protocol; this.h = getHost(); } serviceUrl.prototype.getServiceUrl = function(){ ...

What's the best way to implement two AJAX field validations to prevent button redirection on a website?

Can anyone provide guidance on how to implement two ajax field validations for a button to prevent clicking if the data already exists or redirecting to the same page? I am seeking assistance with this issue. Below is the ajax code snippet: function vali ...

Tips for preventing a page refresh using HTML, JQuery, AJAX, and PHP

I need assistance with transferring the value of a selected radio button to a PHP session variable using Javascript/AJAX. Everything seems to be working fine, except that the page refreshes each time. Is there a way to prevent this from happening? Below i ...

Guide on adding an item to the end of an array with an arrow function

const appendElement = (item) => { return (list) => { }; }; Add a new item to the end of the list. Parameters item (any): The item to add. Output (Array) => Array: Generates a closure that duplicates the original list with the added ite ...

Steps to resolve the Error: $injector:unpr Unknown Provider in AngularJS when establishing a connection to a Laravel database

Recently, I've delved into learning AngularJS and attempting to create a basic webpage that connects AngularJS with a backend Laravel database by following some tutorials. However, I keep encountering an error message stating: Error: $injector:unpr ...

Determine the length of audio files in a Node.js backend

Currently, I am facing a challenge in calculating the duration or length of an audio file. The process involves uploading the audio file to S3 and then retrieving it in lambda for processing. Despite utilizing a library, I have encountered limitations in ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...

Best practices for authenticating methods with Google signin in Angular projects

I have made significant progress towards getting the Google signin feature to work, reaching 95% completion. However, I am currently facing two issues with the code. Here is a simplified version of my current implementation: loginWithGoogle(): void { //t ...

Enhance the speed of TinyMCE editor within an Angular application

Recently, I integrated tinyMCE into my Angular application using the latest (4.x) version of tinyMCE along with the newest release of angular-ui/ui-tinymce (https://github.com/angular-ui/ui-tinymce). All the code is now minified for improved performance. ...

How can I retrieve the precise location of a loaded .obj file in three.js?

When trying to load the .obj file: loader.load( 'test.obj', function ( objMesh ) { objMesh.traverse( function ( child ) { if ( child instanceof THREE.Mesh ) { child.material = mat2; ...

Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues. File: app/app.component.ts import {Component, OnInit} from 'angular2/core'; import {Http} from 'angular2/http'; import {httpServiceClass} fro ...

In JavaScript, why does the value 0x000000 pass as valid syntax?

As I delve into the world of THREE.js, one thing that caught my attention is how object colors are specified using 0x followed by a hex value. What exactly does this signify? Can these be considered valid variable names? What is the mechanism behind thei ...

Listening for events from an iframe can be achieved using a jQuery event listener on the parent element. However, transitioning to using

I'm exploring various methods to attach event listeners for custom events from an iFrame. While I can effectively listen to events from the iFrame using jQuery, I seem to face difficulties achieving the same with plain JavaScript code. I would greatl ...

Python for Asynchronous HTTP Requests

I am currently working on a Python script to extract the value of the href attribute from an anchor element on a web page. The challenge is that the div element containing the anchor element's content is loaded through AJAX jQuery calls when the web p ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Is my JQuery width() function giving incorrect value results?

Currently, I am facing a situation similar to the following: We have two popup windows that are quite alike. These popups are generated by a factory in JavaScript, allowing them to share common events and functions. One such function is our custom resize ...