简体   繁体   中英

ng-click within ng-repeat

In AngularJS, I have an array of colors that have a title and a type . I display all the colors as a list.

Now I would like to add a menu that allows the user to select to only show the colors of a particular type . For this purpose, I have another array that contains colortypes. This is also displayed as a list.

Now I would like to click on a colortype to reduce the list of colors to only those colors that have the selected color.type . For that I use a filter:

<ul>
    <li ng-repeat="color in colors | filter:search">
        {{ color.title }}
    </li>
</ul>

With a manual list of colortypes, it all works fine:

<ul>
    <li>
        <a href="" ng-click="search.type = 'primary';">
            Primary
        </a>
    </li>               
</ul>

However, when I use an array of colortypes as described above, the click does nothing:

<ul>
    <li ng-repeat="colortype in colortypes">
        <a href="" ng-click="search.type = '{{ colortype.title }}';">
            {{ colortype.title }}
        </a>
    </li>               
</ul>

I suppose this has something to do with the ng-click being placed within the ng-repeat (or maybe the scope of the = assignment)? How can I fix the problem?

In ngClick directive you specify not JS code, but expression.

So you can just use <a href="" ng-click="search.type = colortype.title"> and it will work (note: no interpolation by {{}} )

Since ng-repeat creates child scopes, ng-click is referencing the child scope rather than the controller's scope. Here are two options to deal with this.

1) A quick and dirty way is to access the original scope using $parent .

Change your ng-click to something like this:

<a href="#" ng-click="$parent.search.type = colortype.title;">
    {{ colortype.title }}
</a>

See $parent solution in JSFiddle

This approach can break down if the above template is nested or becomes nested. Then you would need to access the controller scope with $parent.$parent... etc.

2) A better approach is to create a function on the controller's scope which returns a reference to the scope. Because of prototypal inheritance , you can access the controller scope functions from the child scope.

function ColorCtrl($scope) {      
    $scope.getColorCtrlScope = function() {
         return $scope;   
    }
    .....
 <a href="#" ng-click="getColorCtrlScope().search.type = colortype.title;">
     {{ colortype.title }}
 </a>

See better solution in JSFiddle

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