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 add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...

Instruction on inserting NativeBase footer into my React Native application?

As someone new to React Native, I am trying to include a footer bar in my app. Below is the code snippet from my dashboard.js file where I attempted to add the footer bar, but it doesn't seem to be working as expected: import React, { memo } from &ap ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Posting a URL on Facebook

I shared a link on Facebook http://35.154.102.35/index.html#/shareProfile, but instead of redirecting to my link, it redirects to the profile of the person share.profile. How can I fix this issue? HtmL: <div class="share-links"> <a href="h ...

There are no warnings or errors when running Yeoman grunt build, however, the dist folder that is generated is not functioning

When working on an Angular application, I typically run either grunt build or grunt serve:dist to generate my production files and deploy them to a remote server. Despite everything appearing fine with no warning messages in the Yeoman logs and yo doctor g ...

How to update an object property in React using checkboxes

I am currently navigating the world of react and have encountered a challenging issue. I am in the process of developing an ordering application where users can customize their orders by selecting different ingredients. My approach involves using checkboxe ...

"Get Recommendations for Slug Name" API Request in AngularJS and Express Application

One feature I want to implement in my app is the ability for users to set the slug name (URL) for documents, while also ensuring that there is control in place to prevent users from overriding each other. To achieve this, I have decided to create a separat ...

Sending a value to a different Ionic page based on a specific condition

Here is the code snippet from my app.js: var app = angular.module('dbpjkApps', ['ionic']) app.controller('kategoriCtrl', function($scope) { $scope.listKat = [ {kat: 'math'}, {kat: 'physics'}, ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

Display different divs based on the number of clicks with the help of ng-show, ng-click, and ng-init

I am looking to display one div by default. Upon clicking a button, I want to show the second div and then upon another click, show the third div. I have experimented with ng-if and ng-show without success. <table class=""> &l ...

Tips for preventing child elements from becoming distorted when the parent element is resized

How can I prevent rotated child elements from skewing when the parent element is scaled? Here is the code snippet that I am working with: <svg viewbox="0 0 500 500"> <g class="parent" transform="matrix(1.71341 0 0 1 -42.302 0)"> <path ...

Creating interactive web pages for scheduling tasks

I'm struggling with how to implement this concept. Imagine I have a School website that features a schedule page for 30 upcoming courses. When a course is clicked, it should lead to a new page displaying specific information about that course (such a ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

How to activate a window that's been minimized in Chrome

I am experiencing an issue with a button that is supposed to open a new window as a popup below the parent page. It works correctly in IE and Firefox, but in Chrome, the popup appears on top of the parent window. Can someone please provide a solution? Fo ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

What is the best way to automatically change a variable in an AngularJS $scope?

My current project involves rendering a list of records to my HTML page, similar to this example taken from: https://www.w3schools.com/angular/ng_ng-repeat.asp <body ng-app="myApp" ng-controller="myCtrl"> <h1 ng-repeat="x in records">{{x}}&l ...

What is the significance of incorporating vinyl-source-stream into gulp in my workflow?

Recently, I've been experimenting with gulp and browserify to convert my .jsx files into .js files. var gulp = require('gulp'); var browserify = require('browserify'); var reactify = require('reactify'); gulp.task(&apos ...