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-ifwhen using my customdirective. 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-ifwhen defining my customdirective.
<!-- 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