0

I need to use a variable as the condition in the ng-if directive, which is set in parent div using ng-init.

<div ng-repeat="item in list" ng-init="flag = false">
  <div>
    <div ng-if="item == a" ng-init="flag = true">
      <!-- Some html code -->
    </div>
    <div ng-if="item == b" ng-init="flag = true">
      <!-- Some html code -->
    </div>
  </div>
  <div ng-if="flag == false">
    <!-- Some html code -->
  </div>
</div>

Can anyone tell me how to get this done?

Edit

I wanted to check whether each item in a list (list_a) is present in another list (list_b).

And for each item in list_a, display one div if present or display another div if not present in list_b.

naseem
  • 13
  • 2
  • 11
  • 1
    The `ng-init` directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of `ngInit`. For more information, see [AngularJS `ng-init` Directive API Reference](https://docs.angularjs.org/api/ng/directive/ngInit). New AngularJS developers often do not realize that `ng-repeat`, `ng-switch`, `ng-view`, `ng-include` and `ng-if` all create new child scopes. See [What are the nuances of scope inheritance in AngularJS?](https://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs) – georgeawg Nov 21 '18 at 19:56

2 Answers2

1

forget about ng-init, create simple directive and include that wherever you need

<div ng-repeat="item in list">
    <div>
        <div ng-if="item == a">
            <!-- Some html code for a -->
        </div>
        <div ng-if="item == b">
            <!-- Some html code for b-->
        </div>
    </div>
    <div ng-if="item != a && item != b">
        <!-- Some html code -->
        <!--or some directive-->
    </div>
</div>
Dmitri Algazin
  • 3,332
  • 27
  • 30
  • I am using another list to store the list of items(a,b,..). In that case, what is the best way? – naseem Nov 21 '18 at 17:48
  • try to figure out yourself. try to understand what you want. angular gives you the way to write conditional tags like ng-if ng-show, based on them you could show/hide big html blocks – Dmitri Algazin Nov 23 '18 at 15:31
0

To check whether the item, in list_a, is present in the list_b and display a block if present, I used

<div ng-if="list_b.indexOf(item)+1">

And to display another div if item is not present in the second list,

<div ng-if="!(list_b.indexOf(item)+1)">

naseem
  • 13
  • 2
  • 11