I know how to make a view condition in AngularJS, that will display or hide dom element dependent on the condition:
<div ng-show="{{isTrue}}">Some content</div>
but how do I create a render condition that determines whether to render or not the div?
Update for angularjs 1.1.5 and above users (not supported in 1.0.7):
Related commit: https://github.com/angular/angular.js/commit/2f96fbd17577685bc013a4f7ced06664af253944
Angular now have a conditional rendering directive: ngIf
.
Usage:
<div ng-if="conditional_expression"></div>
Note that when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored
Documentation: directive-ngIf
For legacy angularjs users:
ngShow
directive conditionally hides/shows the element. This is going to be changed in one of the new stable releases, it is now available in the unstable
release as with 1.1.5
.
If you want to conditionally add/remove items on DOM, use can use ngSwitch
.
<div ng-switch="showMe">
<div ng-switch-when="true">Hello!</div>
</div>
Actually, this directive has been created for handling cases for more than 1, but you can use it that way too. See this answer for examples of more sophisticated usages.
Recommended way is to use ng-include
Example: http://jsfiddle.net/api/post/library/pure/
<div ng-app="">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
Content of template1.html
</script>
<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
Content of template2.html
</script>
</div>
There are at least two ways of doing that:
For simple components, I recommend sticking to the rendering function. Very easy to understand.
$scope.render = function(condition) {
return condition ? "This is rendered when condition == TRUE" : "This is rendered when condition == FALSE";
};
and simply include it in your HTML, like so:
{{render(true)}}
You can also wrap this up with angular directive, which will give you very nice markup and unlimited possibilities!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With