0

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> 
3
  • 3
    Use quotes in the string comparison. ng-class="{'red':color== 'red', 'blue': color== 'blue'}" Demo Commented Apr 13, 2016 at 7:21
  • You Equality to an object but in input you pass a string Commented Apr 13, 2016 at 7:22
  • You are comparing if undefined equals to undefined Commented Apr 13, 2016 at 7:28

2 Answers 2

4

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.

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

5 Comments

Doesn't answer why blue by default
Because with the broken comparison blue is applied, and it has the highest precedence for the background.
Yeah, I corrected that statement. Angular's comparison works a bit differently (it doesn't throw a ReferenceError for one).
In Angular terms then: model with no value equals non existing variable.
1

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.

6 Comments

But then same was case of red. Then why not red ?
Try to swap like this: 'blue':color==='blue','red':color==='red' and it will be red ;)
Ho ho ... Fred still question is same, why not first comparison and only the last or second one!
Cause you use the '==' comparator and not the '==='. With == -> null == undefined return true. With === -> null === undefined return false.
@Peterson Inspect your DOM. Both classes should be applied. But in your CSS rules, blue overrides red!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.