Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active December 6, 2015 18:13
Show Gist options
  • Save khoand0000/2d0ed848bbf540f6bb43 to your computer and use it in GitHub Desktop.
Save khoand0000/2d0ed848bbf540f6bb43 to your computer and use it in GitHub Desktop.
using ng-if and ng-show with directive

Carefully when using ng-if with directive. My situation is that I want to show my directive when it meet a condition. There are 2 ways achieve it:

  • Solution 1: using ng-if when using my custom directive. The solution is working normally. --> UPDATE 2015-12-07: use the solution
<!-- template.html: I use `directive` here -->
<!-- data is array, I will show array if data.length > 0-->
<my-custom-directive ng-model="data" ng-if="data.length > 0"></my-custom-directive>
  • Solution 2: using ng-if when defining my custom directive.
<!-- template.html -->
<my-custom-directive ng-model="data"></my-custom-directive>
<!-- my-custom-directive-template.html -->
<div ng-if="data.length > 0">
  <div ng-repeat="item in data">
    <!-- doing something -->
  </div>
</div>

The solution is not working. Why? Because data is promise when calling webservice, when passing data to my-custom-directive, data hasn't still resulted, so ng-if in my-custom-directive-template.html is applied, <div> is removed from DOM. After data has result, html code <div ng-repeat="item in data"> in the directive will not applied/renderred (I though it. I think it is right for directive case because directive just has only root node. It's not right for normal template). To fix it, using ng-show instead of ng-if, like that

<!-- my-custom-directive-template.html -->
<div ng-show="data.length > 0">
  <div ng-repeat="item in data">
    <!-- doing something -->
  </div>
</div>

UPDATE 2015-12-07: the solution has problem: sometime directive didn't showed even data.length > 0 is right. angular didn't remove ng-hide after data has result even directive is still renderred fully. --> Using solution 1

Why using solution 1 instead of solution 2? Because I will use the directive everywhere with ng-if always. I don't want it. --> UPDATE 2015-12-07: Using solution 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment