Paddy Paddy - 6 months ago 17
AngularJS Question

How to access controller-variables in multiple templates

Hi I´m new to Angular JS, and I am trying to create a "lightbox" by showing or hiding a div that fills the screen. However, the "ng-click" event and the div are on different templates.

First Template (where the div is supposed to show up):

<body ng-app="portfolio" ng-controller="lightboxController" >

<div ng-show="lightbox" class="lightbox">
<p ng-click="checkLightbox()">go back</p>

<p>{{message}}</p>

</div>



<div class="top-menu">
<a href="#portfolio" class="top-menu-button">portfolio</a>
<a href="#about" class="top-menu-button">about</a>
<a href="#contact" class="top-menu-button">contact</a>
</div>


<div id="content-wrapper">
<div id="main-content">
<div ng-view></div>
</div>
</div>



</body>


Relevant controller:

app.controller('lightboxController', function($scope) {

$scope.checkLightbox = function(){

$scope.lightbox;

lightbox= !lightbox;

console.log(lightbox);

};
$scope.message = 'Everyone come and see how good I look!';


});


Second Template (where the ng-click event is):



<div class="grid">

<div class="grid-item dreiD video" ng-click="checkLightbox()">
<img src="data/portfolio/logo-animation/thumb.gif" class="thumb"/>


The error message says: ReferenceError: lightbox is not defined

Answer

Do as below: Your html look like

    <body ng-app="app" ng-controller="lightboxController" >
    <div ng-show="lightbox" class="lightbox">
    <p ng-click="checkLightbox()">go back</p>

    <p>{{message}}</p>

</div>
  <div class="top-menu">
            <a href="#portfolio" class="top-menu-button">portfolio</a>
            <a href="#about" class="top-menu-button">about</a>
            <a href="#contact" class="top-menu-button">contact</a>
        </div>
        <div id="content-wrapper">
            <div id="main-content">
                <div ng-view></div>
            </div>
        </div>
  <div class="grid">
    <div class="grid-item dreiD video" ng-click="checkLightbox()">
      <img src="data/portfolio/logo-animation/thumb.gif" class="thumb"/>
    </div>
  </div>
</body>

Angular controller look like:

var app = angular.module('app', []);
app.controller('lightboxController', function($scope) {

    $scope.checkLightbox = function(){

        $scope.lightbox;

        $scope.lightbox= !$scope.lightbox;

        console.log(lightbox);

    };
    $scope.message = 'Everyone come and see how good I look!';
});

You can run this by clicking here

Comments