Adding a dynamic generated CSS(Cascading Style Sheet) to the AngularJS view with example.

A dynamic generated CSS (Cascading Style Sheet) at the controller can be bind to the HTML View using ng-bind-html attribute with in the style tag. This example uses angular-sanitize.js which removes the dangerous token from the dynamically generated style string. It uses the ng-keyup AngularJS HTML attribute to update the background colour value on KeyUp event. The values inside the text-box taken as the background colour value.

Demo:

Enter the background colour value: #

Note: This example uses angular-sanitize.js which removes the dangerous token from the dynamically generated style string.


Example Program:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
 
<body>
 
	<div ng-app="myApp" ng-controller="myCtrl">
		<style ng-bind-html="myStyle"></style>
		<span>Enter the background colour value:</span>
		<span><input type = "text" ng-keyup="updateChanges()" ng-model = "bgcolour"></span>
		<br/>
		<div class="codeexpertz">
		</div>
 
	</div>
 
	<script>
        var app = angular.module("myApp", ['ngSanitize']);
        app.controller("myCtrl", function($scope) {
            $scope.bgcolour = '11acfd';
            $scope.updateChanges = function(){
                $scope.myStyle= '.codeexpertz { background-color: #' + $scope.bgcolour + '; height: 100px; width: 100px; border: 1px #000 solid}';
            }
            $scope.updateChanges();
        });
    </script>
 
</body>
 
</html>
Category: