0

i have html like this

 <div ng-controller="newcontroller">
     <div class="firstdiv"  ng-show="show">welcome</div>
      <button ng-click="newfunction">click</button>
 </div>

js file like this

  app.controller('newcontroller',function($scope)
  {
         $scope.show=false
         $scope.newfunction=function()
         {
                $scope.show=true;

         }

  });

i have css like this css

.firstdiv { background:green; }

.newclass{background:black;}

Here i am doing that when i click on click button i am showing welcome message. i want to make changes in css dynamically for that div. so i have another css class name called newclass .so when i click on click button i have to apply that new class for making changes in css ....how to do that?

3 Answers 3

1

Use ng-class with expressions to check scope variables

Here's example that doesn't require any function in scope to acheive what you want.

<div ng-class="{newclass : toggle,firstdiv: !toggle} ">welcome</div>
<button ng-click="toggle=!toggle">click</button>

In scope:

$scope.toggle=false;

Using this approach you don't need to write methods to change your elements, they can be changed by simply checking state of a variable within scope

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

index.html

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body ng-app="myApp">
    <div ng-controller="newcontroller">
      <div ng-class="[myclass]">welcome</div>
      <button ng-click="newfunction()">click</button>
    </div>

    <script data-require="[email protected]" data-semver="1.0.8" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>    
    <script src="script.js"></script>    
  </body>

</html>

script.js

'use strict';

var app = angular.module('myApp', []);

app.controller('newcontroller', ['$scope',
  function($scope) {

    $scope.myclass = 'firstdiv';

    $scope.newfunction = function() {
      $scope.myclass = 'newclass';
    };

  }
]);

style.css

.firstdiv { background: green; }
.newclass { background: yellow; }

Working example: http://plnkr.co/edit/oCZGOM?p=preview

1 Comment

rarely need a function just for class change...rather ng-class allows expression to check a scope variable
0

I think you should describe all states of your button in CSS. Then no need to change anything realtime.

Have a look here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.