What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "cambiar desde el hijo," it works but subsequent clicks on "cambiar desde el padre" do not function properly.

Here is the JavaScript code:

 angular.module('starter.controllers', [])

  .controller('padre', function ($scope) {

    $scope.mensaje = "hola";

    $scope.cambiarPadre = function () {
      $scope.mensaje = "texto modificado desde el padre";
    };


  })

  .controller("hijo", function ($scope) {


    $scope.cambiarHijo = function () {
      console.log('entro a cambiar hijo : ');

      $scope.mensaje = "texto modificado desde el hijo";
    };

    $scope.cambiarPadreDesdeHijo = function () {
      console.log('entro a cambiar hijo : ');

      $scope.$parent.mensaje = "texto modificado desde el hijo";
    };

  })

And here is the HTML code:

<ion-view view-title="Dashboard" ng-controller="padre as p">
  <ion-content class="padding">

    FROM PADRE
    <br>

    padre:{{mensaje}}
    <br>
    hijo:{{mensaje}}

    <br>
    <br>


    <button ng-click="cambiarPadre()">cambiar desde el padre</button>


    <div ng-controller="hijo as h">

      FROM HIJO without anything
      <br>
      without parent:
      <br>
      padre:{{mensaje}}
      <br>
      hijo:{{mensaje}}

      <br>
      <br>

      with parent:
      <br>
      padre:{{$parent.mensaje}}
      <br>
      hijo:{{$parent.mensaje}}
      <br>

      <button ng-click="cambiarHijo()">cambiar desde el hijo</button>
      <br>

      <br>
      <button ng-click="cambiarPadreDesdeHijo()">cambiar padre desde hijo</button>
    </div>


  </ion-content>
</ion-view>

Answer №1

Accessing a value from another controller may not be the most ideal approach. Consider using a service to store and share data between controllers for more efficient communication. If you're looking to implement inheritance between controllers, check out some tips from this discussion. Additionally, it's important to note that issues with parent-child relationships in directives like ion-* could also impact functionality. The root of the problem may stem from differences in variable definitions due to the nature of JavaScript's prototypical inheritance model (learn more here).

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

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

Gauging Screen Size: A Comparison between Media Queries and JavaScript for Adjusting Div Position

I am currently facing an issue with the banner on my website. It contains a slider and has a position set to absolute. The problem arises when viewing it on smaller screens, as only the left side of the wide banner is visible. Initially, I tried using med ...

How to insert a span element within a link tag in Next.js/React.js

Looking to create a breadcrumb using microdata in a Next.js and React.js project. Initially, I tried the following: <li itemProp="itemListElement" itemScope itemType="https://schema.org/ListItem"> <Link href={'/index&a ...

Preserve a retrieved value from a promise in Angular

Upon loading the page, the dropdown menu is populated with various values (such as 1, 2...7). However, when attempting to set a specific value based on a certain condition within a promise, it doesn't seem to work. How can this issue be resolved? htm ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Unexpected issue: Angular view is failing to display jade templates

I'm facing an issue while setting up angular with ng-route using JADE. I am unable to connect to my templates where I have stored the HTML files. Below are the steps involved. I know it's a bit lengthy, but I wanted to provide all the details. An ...

What is the best way to trigger a new css animation on an element that is already in the midst of

Let's talk about an element that already has an animation set to trigger at a specific time: .element { width: 100%; height: 87.5%; background: #DDD; position: absolute; top: 12.5%; left: 0%; -webkit-animation: load 0.5s ease-out 5s bac ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Determine if a key begins with a specific string within an object and retrieve the corresponding value

If I have an object like this: let fruitSong = {'apple song':12, 'banana song': 24} Object.keys(fruitSong).forEach(e=>{ if(e.startsWith('apple')){ console.log(fruitSong[e]) } }) Is there a different meth ...

Removing a parameter from a link in Vue.js: A step-by-step guide

I currently have the following list of URLs: http://example.com/post?st=1&plt=123&number=1 http://example.com/post?st=1&plt=[exp]&number=1 http://example.com/post/view/12?ex=1&plt=123 http://example.com/post/edit/12?ex=1&tes ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

When using Array.prototype.map(callback, thisArg), the second parameter is disregarded

Currently, I am developing a small game using Node.js and aiming to offer support for two different languages. To display the translated lists of various game modes along with their descriptions, I have implemented Array.prototype.map(callback, thisArg). ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; Interestingly, when accessing the ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Discover the position of a div relative to another div using ng-drag-drop

I'm currently working on a web application that allows users to create their own identity cards. For this project, I am incorporating the ng-drag-drop library from https://www.npmjs.com/package/ng-drag-drop. The main goal is to obtain the coordinate ...

Angular 7 three-dimensional model display technology

Looking for advice on creating a 3D model viewer within an Angular 7 project. Currently using the model-viewer web component in JavaScript with success. How can I replicate this functionality and viewer within my Angular 7 application? ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...