$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is handled by "AppointmentController" which has a page outside of the nav linked to it. Once certain steps are completed and you login, the appointment setting takes place within AppointmentController view. However, there is a part where -

EDIT - I just realized that the input below needs to be in a separate controller. When attached to NavController, I want apptLogin() to modify data in the main view which is managed by a different controller.

<input ng-controller="NavController" ng-click="apptLogin(email)" value="Login and Continue" class="btn btn-default pull-left" >

$scope.apptLogin = function(email){
  $http({
    method: 'POST',
    data: {email: email},
    url: '/common_includes/ajax/validateUser.php',
  }).then(function successCallback(response) {
      if(response.data.status == 0){
        var login_message = '<div class="alert alert-danger" role="alert">'+response.data.message+'</div>';
        $('#login_modal .modal-body').html(login_message);
        $('#login_modal').modal();
        $interval(function(){
          $('#login_modal').modal('hide');
        }, 1400, 1);
      }
      if(response.data.status == 1){
        $scope.appt_history = true;
        console.log($scope);
        var login_message = '<div class="alert alert-success" role="alert">'+response.data.message+'</div>';
        $('#login_modal .modal-body').html(login_message);
        $('#login_modal').modal();
        $interval(function(){
          $scope.click_login = false;
          $('#login_modal').modal('hide');
        }, 1400, 1);
      }

The above code snippet should toggle the hide/show property, but it's not working as expected. -

$scope.appt_history = true;

I am confused because even though console.log($scope) shows that $scope.appt_history is true, the hide/show behavior doesn't change. What could I be missing here?

Answer №1

If you're looking for a simple way to share data between controllers, one option is to inject $rootScope into each controller. However, this is not the recommended approach.

Instead, I suggest using a service. Services are easy to implement and allow for seamless data sharing across controllers without cluttering the root scope.

To begin, create a service and define the shared property within its constructor:

app.service('sharingSvc', function() {
  this.sharedValue = 'initialized';
});

Next, inject the service into any controllers that need access to the shared property:

app.controller('pageOneCtrl', function($scope, sharingSvc) {
  $scope.pageOneSare = sharingSvc;
});

For a demonstration on how to implement this using a service, check out this basic Plnkr example. This should provide a good starting point for implementing data sharing in your AngularJS application. Good luck!

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

Reducing an array group using index in JavaScript: A beginner's guide

Do you have coding questions? Check out this sample array group: myArray = { tab1 : [], tab2 : [], tab3 : [], tab4 : [] } I'm looking to always retain the first tab (tab1) and an additional tab based on an index (ranging from 2 to 4) For instance, ...

Restricting user access to a route based on its type to enhance security and control

Currently, I have a React, Redux, and Next.js app up and running. Within my redux store, there is a user object that contains an attribute called "type". Each type of user has its own set of "routes" they are allowed to access. I am looking for the most e ...

Searching for a different method in JavaScript that can add items without duplication, as the prependTo function tends to insert multiple items

Every time my code runs successfully, a success message is generated and displayed using prependTo within the HTML. However, the issue arises when the user performs the successful action twice, resulting in two success messages being shown on the screen. ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

Capture a screenshot of an element in either jpg or png format and proceed to save it to your device using Javascript

I am looking to create a JavaScript function that can capture a screenshot of an element and then allow the user to download it. <body> <h1>Sample text</h1> <h2>Sample text</h2> <table width="1080px" height=" ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Having trouble converting the file to binary format in order to send it to the wit.ai api through node.js

I am having trouble converting an Audio file to Binary format for sending it to the Wit.AI API. The node.js platform is being used for this purpose. On the front-end, user voice is recorded using the Mic-recorder Module. Any guidance or suggestions would b ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Call a React component from an external JavaScript file

I am working on a react application that has a bundle.js file created using webpack containing all the necessary code. Recently, I started developing a separate dotnet application and I need to display the main 'App' component from my react appl ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

Ways to determine the length of a string that includes zero or negative width characters such as u0007 or 

Consider the following scenario: I have a string 'aa\b\u0007\u0007' var myString = 'aa\b\u0007\u0007'; console.log(myString); //=> 'a' (plus 2 beeps) console.log(myString.length); //=> 5 ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

Tips for distinguishing between elements in React

I am facing an issue with zooming images on mouse hover using CSS. I have a code snippet that works well, but it zooms both images simultaneously. How can I differentiate between mouse movements over different elements in ReactJS? Here is the code: .styl ...

The transition effect is not activated when using the MUI Drawer with react-router-dom

My goal was to merge the persistent drawer similar to the example on the MUI website with react-router-dom. However, I encountered a problem where the transition effect no longer seems to work properly. The paragraph does not resize to accommodate the open ...

Grids designed in the style of Pinterest

Seeking advice on aligning divs in a Pinterest-style layout. Currently, my setup looks like this: https://i.sstatic.net/erlho.png But I want it to look more like this: https://i.sstatic.net/K9FnD.png Would greatly appreciate any tips or suggestions on ho ...

Sending data to functions

Hello all, I'm a beginner with Vue so please bear with me :) I am facing a challenge where I have a function that retrieves user attributes and based on those attributes, I need to run a GraphQL query in another function. Both functions are under the ...

Implementing an active class in a React render method

Working with UI Kit Components <ul className='uk-nav'> {languages.map(function (lang) { return ( <li style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : n ...

The autocomplete feature fails to properly highlight the selected value from the dropdown menu and ends up selecting duplicate values

After working on creating a multiple select search dropdown using MUI, my API data was successfully transformed into the desired format named transformedSubLocationData. https://i.stack.imgur.com/ZrbQq.png 0: {label: 'Dialed Number 1', value: &a ...