Having trouble retrieving the latest value of a scope variable when dealing with multiple partial HTML files controlled by a single Angular controller

In my Angular controller, I have an HTML file that includes two partials. Here is a simplified version:

HTML:

<!DOCTYPE html>
<html>
   <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   <body>
      <!-- It calls one of these two partials for a navigation bar. -->
   </body>
</html>

HTML 1:

      <div ng-app="myApp" ng-controller="myCtrl">
         Name: <input type="text" ng-model="name" ng-click="myfunction()">
      </div>

HTML 2:

      <div ng-controller="myCtrl">
         <br>
         Person Name: {{new_name}}
      </div>

Controller:

var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope) {
      $scope.name = "";
      $scope.new_name = "";

      $scope.getQuery = function() {
        $scope.new_name = $scope.name;  
      };
});

Currently, in HTML 2, {{new_name}} displays as an empty string because it was declared as such in the controller. However, I would like it to dynamically update based on the input from HTML 1. How can I achieve this?

Answer №1

Each time you include ng-controller="myCtrl" in your code, a brand new controller instance is generated, resulting in the creation of a fresh scope. By inspecting the elements in your browser and setting a breakpoint at the start of the controller, you can observe that multiple instances are formed.

It is advisable to use separate controllers for each view. For displaying multiple views on a single page, consider exploring Ui-router named views.

To facilitate data sharing among these controllers, you have several options:

  1. Create a service and inject it into both controllers
  2. Utilize $scope, with a parent $scope accessible to child controllers (This can be easily achieved using UI-Router nested states)

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

Encountering a syntax error with the spread operator while attempting to deploy on Heroku

I'm encountering an error when attempting to deploy my app on Heroku: remote: SyntaxError: src/resolvers/Mutation.js: Unexpected token (21:16) remote: 19 | const user = await prisma.mutation.createUser({ remote: 20 | data: { r ...

Issue with angularjs ui.router delaying the rendering of ui-view

I've been working on implementing ui-router in my project. Here is the core module setup: var core = angular.module('muhamo.core', ['angular-loading-bar', 'anguFixedHeaderTable', 'ui.router']); For the tra ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

Missing Angular reference in WordPress

Have you ever tried integrating Angular into a WordPress plugin? I recently attempted to do so by adding the following code: wp_register_script('jquery-custom', ("http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"), false); ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...

Loop through a variable class name in JavaScript

When working with Javascript, I have a series of elements with identical divs: (....loop, where "count" is a unique number for each column) <other divs> <div class="pie"></div> </div> My goal is to be able to rotate each individ ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

I'm puzzled about what could be behind this error message Error [ERR_HTTP_HEADERS_SENT], especially since I've only sent the response header once. How can I figure out the cause

Here is a snippet of code from my routes file: router.get('/api/', async function(request, response){ let entries = await Entries.find({}, function(error){ if(error) console.log(error); }); let catArray = []; entrie ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...

Creating a dynamic list in HTML by populating it with randomly selected words using JavaScript

Check out my awesome code snippet function wordSelect() { var words = ["Vancouver", "Whistler", "Surrey", "Victoria", "Kelowna"]; //List of randomly-selected words from above var selectedWords = []; for(let i = 0; i &l ...

Guide to simulating a scope in an Angular unit test using a directive instead of a controller

Recently, I have been working on understanding how to mock a $scope and controller using the $controller constructor. var scope = rootScope.$new(); it('should contain a testVar value at "test var home"', function(){ homeCtrl = $controller(&a ...

Having issues with my CodePen React code and its ability to display my gradient background

I will provide detailed descriptions to help explain my issue. Link to CodePen: https://codepen.io/Yosharu/pen/morErw The problem I am facing is that my background (and some other CSS elements) are not loading properly in my code, resulting in a white bac ...

Determine the height of an image using JavaScript

How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

Securing Communication with HTTPS in Express JS

After purchasing an AlphaSSL from a hosting provider, I received the following files: domain.csr.crt domain.interCert.crt domain.PKCS7Cert.crt domain.rootCert.crt domain.X509Cert.crt However, in order to enable HTTPS on Node.JS using Express, I am aware ...

Using Cypress for drag and drop functionality within shadow DOM

I encountered an issue in cypress with drag and drop functionality within the shadow dom. My attempt to perform a drag event is as follows: cy.get(".shadow-app>div>div:nth-child(1)", { includeShadowDom: true }).trigger("dragstart&q ...

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

Retrieve the value within the $scope when making an HTTP get request, but ensure it is only called once the client code has

On the controller page Expense.js: $scope.getPagedDataAsync = function (pageSize, page) { $scope.largeLoad = todoService.initialize(); todoService.getDataAsync(); $scope.setPagingData($scope.largeLoad, page, pageSize) ...