Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a render condition with AngularJS

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?

like image 343
Alon Avatar asked Jan 23 '13 08:01

Alon


3 Answers

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.

like image 164
Umur Kontacı Avatar answered Nov 06 '22 15:11

Umur Kontacı


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>
like image 2
SunnyShah Avatar answered Nov 06 '22 16:11

SunnyShah


There are at least two ways of doing that:

  • render some partial using templating
  • use simple expression with conditional rendering function (see this fiddle and description below)

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!

like image 1
ŁukaszBachman Avatar answered Nov 06 '22 15:11

ŁukaszBachman