Question

So I'm running through the tutorial for AngularJS:

I have an array defined in the controller and i'm returning different points in the array by calling when i'm looping through ng-repeat {{feature.name}} {{feature.description}}

What i don't understand is lets say i have a third point in the array called "importance" and it's a number from 1 to 10. I don't want to display that number in the html but what i do want to do is apply a different color to the feature if that "importance" number in the array is 10 vs 1

so how do i write an if statement to do this:

i.e.

<p style="**insert if statement: {{if feature.importance == 10}} color:red; {{/if}} **">{{feature.description}}</p>

no idea if that's right but that's what i want to do

Was it helpful?

Solution 7

This first one is a directive that evaluates whether something should be in the DOM only once and adds no watch listeners to the page:

angular.module('setIf',[]).directive('setIf',function () {
    return {
      transclude: 'element',
      priority: 1000,
      terminal: true,
      restrict: 'A',
      compile: function (element, attr, linker) {
        return function (scope, iterStartElement, attr) {
          if(attr.waitFor) {
            var wait = scope.$watch(attr.waitFor,function(nv,ov){
              if(nv) {
                build();
                wait();
              }
            });
          } else {
            build();
          }

          function build() {
            iterStartElement[0].doNotMove = true;
            var expression = attr.setIf;
            var value = scope.$eval(expression);
            if (value) {
              linker(scope, function (clone) {
                iterStartElement.after(clone);
                clone.removeAttr('set-if');
                clone.removeAttr('wait-for');
              });
            }
          }
        };
      }
    };
  });

This second one is a directive that conditionally applies attributes to elements only once without watch listeners:

i.e.

<div set-attr="{ data-id : post.id, data-name : { value : post.name, condition : post.name != 'FOO' } }"></div>

angular.module('setAttr',[]).directive('setAttr', function() {
  return {
    restrict: 'A',
    priority: 100,
    link: function(scope,elem,attrs) {
      if(attrs.setAttr.indexOf('{') != -1 && attrs.setAttr.indexOf('}') != -1) {
      //you could just angular.isObject(scope.$eval(attrs.setAttr)) for the above but I needed it this way
        var data = scope.$eval(attrs.setAttr);

        angular.forEach(data, function(v,k){

          if(angular.isObject(v)) {
            if(v.value && v.condition) {
                elem.attr(k,v.value);
                elem.removeAttr('set-attr');
            }
          } else {
            elem.attr(k,v);
            elem.removeAttr('set-attr');
          }
        });
      }
    }
  }
});

Of course your can use dynamic versions built into angular:

<div ng-class="{ 'myclass' : item.iscool }"></div>

You can also use the new ng-if added by angularjs which basically replaces ui-if created by the angularui team these will conditionally add and remove things from the DOM and add watch listeners to keep evaluating:

<div ng-if="item.iscool"></div>

OTHER TIPS

I do not think there is if statement available. For your styling purpose, ng-class can be used.

<p ng-class="{important: feature.importance == 10 }">

ng-switch is also convenient.

-- update --

take a look at: https://stackoverflow.com/a/18021855/1238847

angular1.2.0RC seems to have ng-if support.

Actually there is a ternary operator in Angular 1.2.0.

<p style="{{feature.importance == 10 ? 'color:red' : ''}}">{{feature.description}}</p>

I think the answer needs an update.

Previously you could use ngIf directive from AngularUI project (code here if you still want to download it), bad news is that it's not maintained any more.

The good news is that it has been added to the official AngularJS repo (unstable branch) and soon will be available in the stable one.

<div ng-if="something"> Foo bar </div>

Will not just hide the DIV element, but remove it from DOM as well (when something is falsy).

ng-class is probably the best answer to your issue, but AngularUI has an "if" directive:

http://angular-ui.github.com/

search for: Remove elements from the DOM completely instead of just hiding it.

I used "ui-if" to decide if I should render a data value as a label or an input, relative to the current month:

<tbody id="allocationTableBody">
    <tr ng-repeat="a in data.allocations">
        <td>{{a.monthAbrv}}</td>
        <td ui-if="$index < currentMonth">{{a.amounts[0]}}</td>
    </tr>
</tbody>

In the case where your priority would be a label, you could create a switch filter to use inside of ng-class as shown in a previous SO answer : https://stackoverflow.com/a/8309832/1036025 (for the switch filter code)

<p ng-class="feature.importance|switch:{'Urgent':'red', 'Warning': 'orange', 'Normal': 'green'}">...</p>

You can also try this line of code below

<div class="{{is_foo && foo.bar}}">

which shows foo.bar if is_foo is true.

What also works is:

<span>{{ varWithValue || 'If empty use this string' }}</span> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top