user972255
user972255

Reputation: 1828

AngularJs - how to check indexOf in a variable?

I have this html code and if the "modalOptions.actionButtonText" contains "delete" then I need to display danger button instead of primary button

Html Code:

<button class="btn btn-primary" data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>

I know we can use "ng-if" to check the condition but is there any way I can use indexOf in angularjs or something else to achieve this?

Upvotes: 1

Views: 11605

Answers (2)

Joe Velez
Joe Velez

Reputation: 140

I wanted something similar, but wrote it in shorthand:

<li ng-class="haystack.indexOf('needle') != -1 ? 'active' : 'inactive'">

Upvotes: 2

jessegavin
jessegavin

Reputation: 75650

Looks dirty, but it works.

See working demo

<button class="btn" 
  data-ng-class="{'btn-primary': modalOptions.actionButtonText.indexOf('delete') == -1,
                  'btn-danger': modalOptions.actionButtonText.indexOf('delete') > -1}"
  data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>

The ngClass directive lets you add/remove classes based on a boolean expression. So here, I am adding btn-primary if "delete" isn't found in the button text and btn-danger if it is.

Upvotes: 2

Related Questions