0

I need to change the mensaje variable from the "padre controller" and visualize it. and change the variable from the "hijo controller" and viceversa, but it's not working

if a click in "cambiar padre" the value change, if a click in "cambiar desde el hijo", it's working, but when I click again in "cambiar desde el padre" it's not working anymore

js

 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";
    };

  })

html

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

    DEL PADRE
    <br>

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

    <br>
    <br>


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


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

      DEL HIJO sin nada
      <br>
      sin parent:
      <br>
      padre:{{mensaje}}
      <br>
      hijo:{{mensaje}}

      <br>
      <br>

      con 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>
Ivan Paredes
  • 465
  • 2
  • 5
  • 20

1 Answers1

1

It's not the proper way to access a value from another controller. If you really want to share data between them you should use a service to store the value and both controllers can change that value. If you really want to do inheritance between the controllers you should try something from this thread. Beside this I'm not sure if the parent of "hijo" will be the "padre" because you use it form ion-* directives. The possible problem why it does not work comes from the nature of javascript (prototipical inheritance) and you probably does not write the same variable that the controller reads.

Community
  • 1
  • 1
akos.bordas
  • 179
  • 1
  • 7