Search code examples
htmlangularjsangularjs-directiveangularjs-scopeangular-controller

Show a div by wrap with another controller doesn't work


I have a button in a div with a controller named controllerBubble. I would like this button show a div controlled by an other controller : controllerDependance. Is it possible to wrap the button in a div and the hidden div with same controller but it doesn't works. This is my HTML :

<div ng-app="app">

  <div ng-controller="mainController" ng-show="myvalue" class="ng-cloak">
    <div id="panelSap" ng-controller="controllerDependance">
      My hidden div
    </div>
  </div>

  <div id="containerDetailsTicket" class="clearfix" ng-controller="controllerBubble">
    Div which contains the button
    <div id="containerButton" ng-controller="mainController">
      <button ng-click="showAlert()">Afficher</button>
    </div>
  </div>

</div>

This is my controllers :

var d3DemoApp = angular.module('app', [])
d3DemoApp.controller('controllerBubble', function() {

});

d3DemoApp.controller('controllerDependance', function($scope) {
  $scope.myvalue = false;
  $scope.showAlert = function() {
    $scope.myvalue = true;
  };
});

d3DemoApp.controller('mainController', function AppCtrl($rootScope, $scope) {
  $scope.myvalue = false;
  $scope.showAlert = function() {
    $scope.myvalue = true;
  };
});

I created a Plunker Any idea what's happening ? Someone can do work on the Plunker. I Hope someone can help me. Thanks a lot.


Solution

  • Look, not sure why you want to have such a nesting of controllers but I am pretty much sure that it ain't good. I'll tell you why. In your code, you are trying to use same controller at two DOM ele. So, they are having 2 different scope $scope and so they are not working.

    I have made a working plunker for you by using $rootScopebut its not a clean approach as you'll be having a global variable ($rootScope.myvalue) declared. Declaring global variable should always be avoided unless forced to.

    Another suggested approach in plunker is to use $emit as event notifier. The $on would take appropriate action when the event is triggered. You can even pass values that too to different controllers.

    Service can also be used to pass values among controllers .

    Let me know if you need more info

    Update 1:

    If you want to remove some div (not hide) then you should try to use ng-if.