AngularJS – dynamic css using ng-style

Angularjs ng-style directive can be used to define inline style attribute which can define dynamic style values using variables.

Usage:

<ANY
  ng-style="expression">
...
</ANY>
// e.g. ng-style="{display: cbValue == true? 'static':'none'}"

Note that expression evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.

Example – Show/hide a div using ng-style and checkbox state

This example will use checkbox state to hide/show a div element using style display.

<div ng-app="myApp" ng-controller='MyCtrl'>
  <input type="checkbox" ng-model="cbValue">Show/Hide<br><br>
  <div ng-style="{display: cbValue == true? 'static':'none'}">
    Hello world
  </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {
  $scope.cbValue = true;
});
</script>
refresh

Example – Show/hide a div using ng-style and checkbox ng-change handler

Same example with a model variable in ng-style and changing the variable in ng-change handler.

<div ng-app="myApp" ng-controller='MyCtrl'>
  <input type="checkbox" ng-model="cbValue" ng-change="styleVal= cbValue ? {display:'static'} : {display:'none'}">Show/Hide<br><br>
  <div ng-style="styleVal">
    Hello world
  </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {
  $scope.cbValue = true;
});
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments