Angular 1.1.5 introduced the ng-if directive. This is the best solution for this particular problem. If you are using an older version of Angular, consider the angular -ui ui-if directive.
If you came here looking for answers to the general question “conditional logic in templates”, also consider:
- 1.1.5 also introduced the ternary operator
- ng-switch can be used to conditionally add / remove elements from the DOM
- see also How to conditionally apply CSS styles in AngularJS?
Original answer:
Here is a not-so-good "ng-if" directive:
myApp.directive('ngIf', function() { return { link: function(scope, element, attrs) { if(scope.$eval(attrs.ngIf)) {
which allows you to use this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type"> <hr> <div ng-if="showFrom(message)"> <div>From: {{message.from.name}}</div> </div> <div ng-if="showCreatedBy(message)"> <div>Created by: {{message.createdBy.name}}</div> </div> <div ng-if="showTo(message)"> <div>To: {{message.to.name}}</div> </div> </div>
Fiddle
replaceWith () is used to remove unnecessary content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images if you want to use ng -show instead of a custom directive. (For the benefit of other readers, John stated on Google+: “Both methods use ng-show, which I am trying to avoid because it uses display: none and leaves extra markup in the DOM. This is a special problem in this scenario because the hidden element will have a background image that will still be loaded in most browsers. ").
See also How to conditionally apply CSS styles in AngularJS?
angular -ui ui-if directive monitors changes in the if / expression condition. My not. Thus, although my simple implementation will correctly update the view, if the model changes so that it only affects the output of the template, it will not correctly update the view if the response of the condition / expression changes.
For example, if the value of a from.name changes in the model, the view will be updated. But if you delete $scope.data.messages[0].from , the name will be removed from the view, but the template will not be removed from the view, because the if-condition / expression is not visible.
Mark Rajcok Dec 29 '12 at 22:34 2012-12-29 22:34
source share