Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs if/else statements

<div class="company_name" ng-controller="CompanyName">
 <h1 class="left">
     {{data.company_name}}
 </h1>
</div>

What I'd like to do is make it so that if data.company_name hasn't been added through an input field, it shows a placeholder "Company name", how can that be done using angularjs?

like image 238
Xeen Avatar asked Sep 10 '13 08:09

Xeen


3 Answers

You can use ng-if and do something like

<div class="company_name" ng-controller="CompanyName">
 <h1 class="left">
     <span ng-if="data.company_name === ''">
       // Some placeholder
     </span>
     <span ng-if="data.company_name !== ''">
       {{data.company_name}}
     </span>
 </h1>
</div>

BTW ngIf is a new directive added in v1.1.5 so you might need to upgrade your angular version

See my plunker here : http://plnkr.co/edit/qiN2XshEpay6e6zzhUKP

like image 198
Nicolas ABRIC Avatar answered Oct 18 '22 18:10

Nicolas ABRIC


One way to keep the code clean is to use a filter. This piece of code adds a class to an active tab.

var filters = angular.module('filters');
filters.filter('ie', function(){
  return function(v, yes, no){
      return v ? yes : no;
  };
});

Template

<li class="{{activeTab == 'home' | ie: 'active-class':''}}">
    Home
</li>
like image 28
Kristo Aun Avatar answered Oct 18 '22 17:10

Kristo Aun


For Using ng-if, ng-else-if, and ng-else in your project use this:

https://github.com/zachsnow/ng-elif

like image 41
Aqib Mumtaz Avatar answered Oct 18 '22 16:10

Aqib Mumtaz