简体   繁体   English

ng-class在'AngularJs'中无法正常工作

[英]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> 

You don't have any variables red or blue defined anywhere, so their value evaluates to undefined , which passes comparison differently than you expect. 您在任何地方都没有定义redblue变量,因此它们的值计算为undefined ,通过比较的方式与您期望的不同。

Compare to the strings 'red' and 'blue' , with quotes. 比较带引号的字符串 'red''blue'

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. 默认情况下,color = null,变量blue是未定义的。 So the expression null == undefined returned true, that's why your paragraph was in blue. 因此,表达式null == undefined返回true,这就是您的段落为蓝色的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM