Search code examples
angularjsangularjs-ng-clickng-style

Angular.js - Changing an Element's CSS by clicking another Element


I'm very new to Angular.js.

I'm grabbing images from a MySQL database and printing them to the screen like this:

while ($row = mysqli_fetch_array($result)){
                echo "<div id='img_div' ng-click='popup()'>";

On the echoed div, I have an ng-click. In app.js, this is currently what I have for the ng-click (purely for testing purposes:

$scope.popup = function() {

// assign a message to the $scope
$scope.message = 'Hello World!';

// use the $log service to output the message in a console
$log.log($scope.message);

};

What I'd actually like to have in that ng-click function is:

modal.style.display = "block";

I'd basically like to set the CSS of another element.

Will I need to apply ng-style in order to do this?


Solution

  • Using ng-style with a $scope variable you can control the display property (or any for that matter):

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.display = 'inline';
      $scope.setDisplayValue = function(value){
        $scope.display = value;
      }
    });
    div#test {
      
      background: red;
      
    }
    <!DOCTYPE html>
    <html ng-app="plunker">
    
      <head>
        <meta charset="utf-8" />
        <title>AngularJS Plunker</title>
        <script>document.write('<base href="' + document.location + '" />');</script>
        <link rel="stylesheet" href="style.css" />
        <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
        <script src="app.js"></script>
      </head>
    
      <body ng-controller="MainCtrl">
        <div id="test" ng-style="{'display' : display}">{{display}}</div>
        <hr />
        <button ng-click="setDisplayValue('inline')">Set Display to inline</button>
        <button ng-click="setDisplayValue('block')">Set Display to block</button>
      </body>
    
    </html>

    Plunker mirror: http://plnkr.co/edit/4vR4SEnz7iX81CWIrShw