ng-class not properly working inside h1?

505 views Asked by At

I'm starting studying AngularJs and I was wondering why my code is not working? I was wondering why the h1 tag is not getting orange with the ng-class="'orange'".

I know that the answer could be quite easy but I'm just starting.

Here is my index.html:

<html ng-app="app">
    <head>
        <style type="text/css">
        </style>

    </head>
    <body>

        <div ng-controller="MainController">
            <h1 ng-class="'orange'">Hello There</h1>
        </div>


        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </body>
</html>

And here my app.js:

var app = angular.module('app', []);

app.controller('MainController', function($scope) {

})

P.s. no errors in the console.

2

There are 2 answers

4
Pankaj Parkar On BEST ANSWER

It must work. Because as a resultant you are giving the class as direct string variable which value is orange with single quotes.

It is the same as that you are defining like scope variable which is returning value from as

<h1 ng-class="class">Hello There</h1>

Code

$scope.class='orange';

Both approaches are one as the same thing.

Update

You need to add css class to get those changes

<style type="text/css">
  .orange {
     color: orange;
  }
</style>

Demo Plunkr

1
Jony-Y On

ng-class is used when you want to have a dynamic or scope related class, if you want to have a static class just use class. I saw your comment, it does not replace any CSS by any means. its just a way to dynamically interchange css classes.

you can use it in several ways, such as:

<h1 ng-class="class">Hello There</h1>

and in the controller

$scope.class='orange';

or with condiotions:

<h1 ng-class="{'danger' : condition}"><Hi</h1>

or tenaric if:

 <h1 ng-class=" condition? 'danger' : 'warning'">Hi</h1>

natuarlly condition is defined in the scope and the '' items are the classes to be added