Deadpool
Deadpool

Reputation: 8240

ng-class not working properly in 'AngularJs'

In following program, as I type red in the input box, the paragraph must turn red in background. Also, why by default I am getting blue background in paragraph (It should be transparent as model is having null value on page load? Can someone help me ?

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script> 
    <style>
    .red{background:red;}
    .blue{background:blue;}
    </style>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 
    <input type="text" ng-model="color" />
    <p ng-class="{'red':color==red,'blue':color==blue}">This is a paragraph.</p>
<script>
    //1 module declaration
    var app = angular.module('myApp', []);
    //2 controller declaration
    app.controller('myCtrl',function($scope){
        //code here
    });
</script> 
</body> 
</html> 

Upvotes: 0

Views: 1105

Answers (2)

Fred
Fred

Reputation: 5006

Try to replace your code with:

<p ng-class="{'red':color==='red','blue':color==='blue'}">This is a paragraph.</p>

By default you had the following expression:

color==blue

By default color = null and the variable blue is undefined. So the expression null == undefined returned true, that's why your paragraph was in blue.

Upvotes: 1

deceze
deceze

Reputation: 521994

You don't have any variables red or blue defined anywhere, so their value evaluates to undefined, which passes comparison differently than you expect.

Compare to the strings 'red' and 'blue', with quotes.

Upvotes: 4

Related Questions