MaximeBernard
MaximeBernard

Reputation: 1100

Questions relative to $scope & controllers

I'm trying to play with 2 controllers speaking to each other but I'm stuck with 2 problems/questions:

  1. $scope.display is not displayed at first in my view. I wonder why.
  2. $scope.display seems to be shared between 2 controllers whereas I read $scope(s) are isolated. I wonder why.
  3. I read on stackoverflow the best to communicate between controllers is to use $rootScope.broadcast & $rootScope.on. Does this apply to this example?

JS

angular.module("superApp", [])
    .controller("headerCtrl", function ($scope) {
        $scope.display = 'hello';
    })
    .controller("homeCtrl", function ($scope) {

    });

HTML

<div ng-app="superApp">
    <div ng-ctrl="headerCtrl">
        <p>{{ display }}</p>
        <div class="bar hello" ng-show="display == 'hello'"> 
            <span>Hello World<span>
            <button ng-click="display = 'bye'">Say bye</button>
        </div>
        <div class="bar bye" ng-show="display == 'bye'">
            <span>Bye Bye</span>
            <button ng-click="display = 'hello'">Say hello</button>
        </div>
    </div>
    <div ng-ctrl="homeCtrl" class="content">
        <button ng-click="display = 'bye'">Say bye</button>
        <button ng-click="display = 'hello'">Say hello</button>
    </div>
</div>

I think I'm missing something... Here's a jsfiddle to test.

Upvotes: 0

Views: 33

Answers (2)

Meetarp
Meetarp

Reputation: 2461

You want to use ng-controller and not ng-ctrl.

<div ng-controller="headerCtrl">

and

<div ng-controller="homeCtrl" class="content">

Why was your code "working"?

When using these directives without a declared controller and its associated scope:

ng-click="display = 'bye'"
ng-show="display == 'hello'"

You basically affect the $rootScope variables and set a new var 'display' in the $rootScope with the value for each click. That's why it was only shown after first click and does not appear when you initially view the page. None of your controllers were actually being used.

See: AngularJS Documentation for $rootScope

Upvotes: 1

Ben Diamant
Ben Diamant

Reputation: 6206

Problem was with the ng-ctrl directive, should be ng-controller

    <div ng-controller="homeCtrl" class="content">

Upvotes: 0

Related Questions