简体   繁体   中英

AngularJS - ng-repeat and ng-show

I got the following code:

<div class="map" ng-controller="DealerMarkerListCtrl">
    <a ng-click="showdetails=!showdetails" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker.left}}px;top:{{marker.top}}px" ng-repeat="marker in dealer"></a>
</div>

and this view:

<div ng-show="showdetails" class="alldealermodal">    
    <div ng-view></div>
</div>

This same "ng-show" stuff is working properly with just one link outside of the ng-repeat but in this ng-repeat it isn't working.
The link shall open an overlay. The ng-view works too.

What am I missing?

Since ngRepeat creates a new scope the showdetails being referenced outside of your ng-repeat is not the same instance as the showdetails being updated in your repeated ng-click .

You can see this post for more details but one way around the new scope(s) is to bind to an object property instead of a primitive type.

This fiddle shows a small example binding to details.show instead of showdetails with:

$scope.details = { show: true };

"What am I missing?"

As @Gloopy already mentioned, you probably didn't realize that ng-repeat creates child scopes (one for each item). In addition, an understanding about how JavaScript prototypal inheritance works is also necessary because each child scope prototypically inherits from the same parent scope, and that affects how JavaScript finds (or creates) properties on scopes.

Note that a number of Angular built-in directives create child scopes: ng-repeat, ng-include, ng-switch, ng-controller, directives (can, but may not). For (much) more information about how prototypal inheritance works, why it is a problem when trying to bind to primitives, and how it relates to Angular scopes, see here .

To extend @Gloopy's answer, there are two other alternatives you could consider:

  1. use $parent inside the ng-repeat to bind to the parent scope property (instead of creating child scope properties):
    <a ng-click="$parent.showdetails=!$parent.showdetails" ...
  2. define a method on the parent scope and call it, thereby also changing a parent scope property (rather than a child scope properties):
    <a ng-click="toggleDetails()" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM