admin管理员组

文章数量:1316023

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?

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?

Share Improve this question asked Jan 6, 2013 at 22:04 Marek123Marek123 1,2117 gold badges39 silver badges78 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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()" ...

本文标签: javascriptAngularJSngrepeat and ngshowStack Overflow