Reputation: 3
I am using angular repeat to populate form's fields dynamically. There is a scenario where I need to to notify user(show ! icon for duplicate fields). Below is code snippet:
<div ng-init="counter = 0">
<div ng-repeat="item in list track by $index">
<div ng-show="{{item.show}}">{{counter+1}}</div>
</div>
<div ng-show="{{counter > 1}}"> ! </div>
</div>
Counter variable only increment if its used like {{counter + $index}}, can it be possible without $index?
Upvotes: 0
Views: 5467
Reputation: 1552
Assigning variables inside html is not officially supported.
But there is always a hack for what you asked:
<div ng-init="counter = 0"></div>
<div ng-repeat="n in [1,2,3,4,5]">
<div style="display:none;">{{ n == 3 ? counter = "World!" : counter = n }}</div>
<p>Hello {{ counter }}</p>
</div>
Notice that I used a non-displayed div for assigning the "counter" conditionally.
Output:
Hello 1
Hello 2
Hello World!
Hello 4
Hello 5
Answer to the 1st comment: When counter == 3, we divide it by 2.
<div ng-init="counter = 0"></div>
<div ng-repeat="n in [1,2,3,4,5]">
<div style="display:none;">
{{ counter = n }}
{{ counter == 3 ? counter = counter / 2 : counter = counter }}
</div>
<p>Hello {{ counter }}</p>
</div>
Output:
Hello 1
Hello 2
Hello 1.5
Hello 4
Hello 5
Answer to the 3rd comment:
I finally understood what you asked. Let me change the way to approach by using ng-if to keep the record of counter. I used ng-init to increment the counter when n is divisible by 2. You need to call $parent.$parent.counter to reach the original counter otherwise ng-if will create its own counter inside the child scope.
<div ng-init="counter = 0"></div>
<div ng-repeat="n in [2,6,5,6,8,9,11] track by $index">
<!-- ngRepeat child scope -->
<div ng-if="n % 2 == 0"
ng-init="$parent.$parent.counter = $parent.$parent.counter + 1"
style="display:none;">
<!-- ngIf also creates a child scope -->
</div>
</div>
<p>Counter = {{ counter }}</p>
Output:
Counter = 4
Upvotes: 2