isherwood
isherwood

Reputation: 61083

Toggling boolean variable from nested AngularJS or Ionic directives

I have a nested list to display comments and replies with 3 levels. I'm toggling dates from time-ago to actual on click by showing and hiding one of two date elements. This works well for each level using ng-click="$parent.swapDate=!$parent.swapDate", but fails to affect other levels.

How can I apply the toggle to all levels of the structure, which looks like the following (simplified)?

<ion-content>
    <div class="list">
        <div class="item" ng-repeat="comment in comments">
            <span am-time-ago="comment.date | amUtc | amLocal" 
              ng-click="$parent.swapDate=!$parent.swapDate" 
              ng-hide="$parent.swapDate">
            </span>

            <span ng-click="$parent.swapDate=!$parent.swapDate" 
              ng-show="$parent.swapDate">
                {{comment.date | amDateFormat: 'D MMMM YYYY @ h:mma'}}
            </span>

            <div class="list">
                <div class="item" ng-repeat="comment in comments">
                    <span am-time-ago="comment.date | amUtc | amLocal" 
                      ng-click="$parent.swapDate=!$parent.swapDate" 
                      ng-hide="$parent.swapDate">
                    </span>

                    <span ng-click="$parent.swapDate=!$parent.swapDate" 
                      ng-show="$parent.swapDate">
                        {{comment.date | amDateFormat: 'D MMMM YYYY @ h:mma'}}
                    </span>
                </div>
            </div>
        </div>
    </div>
</ion-content>

I'd prefer to not use a global variable or a service for such a simple thing. Thank you.

Upvotes: 0

Views: 165

Answers (2)

isherwood
isherwood

Reputation: 61083

Marks' answer helped send me in the right direction. Actually, I was reading a good article that mentions the 'dot' best practice for scope variables, and I returned to this question to investigate.

Simply replacing

$parent.swapDate

with

comments.swapDate

in all instances resolves the problem.

Upvotes: 0

Marks
Marks

Reputation: 347

inside ng-click or ng-hide or other ng-xx,the $parent.var become isolated once you change it;thus other div won't change. try put it in an object e.g. $parent.var_obj={var:xx}

Upvotes: 1

Related Questions