Miguel Moura
Miguel Moura

Reputation: 39384

Add CSS class using angular

I have the following on Angular controller scope model:

$scope.model = {
  subscriber: { email: '', name: '' },
  notice: { text: '', type: '' }
}

I need to display a P tag whenever notice.text is not empty and add a CSS class equal to notice.type. So I have:

<p class="notice" data-ng-bind="model.notice.text" data-ng-if="model.notice.text != ''"></p>

P tag has always the class "notice". But I need to add the class contained in $scope.model.type if it is defined.

How can I do this?

Side question: Is there a better way to show / hide the P tag instead of using data-ng-if?

Upvotes: 1

Views: 240

Answers (1)

Satpal
Satpal

Reputation: 133403

You can use ngClass directive

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

Code

ng-class="model.notice.text != '' ? model.notice.type : ''"

Upvotes: 2

Related Questions