有没有办法有条件地将数据从`ng-repeat`传递给其他元素?

时间:2015-08-23 09:57:07

标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-filter

我正在循环一个数组,通过条件我找到一个值。但是如何将该条件值传递给另一个元素?

示例:

<h1>{{title}}</h1> //how to get here?
<ul class="naviPrCatgInfo">

    <li ng-repeat='subProject in viewProject.SubProjectIds' ng-class="{'selected' : subProject.Id === subProjectId;}" > //how to pass?
        <a ng-class="subProject.Name | trimSpace" ng-href="" ng-click='changeSubProCat(subProject)'>
            {{subProject.Name}} {{subProject.Id}}
        </a>
    </li>

</ul>

1 个答案:

答案 0 :(得分:3)

不要在ng-repeat中声明新变量,因为这会添加到ng-repeat创建的子范围内。

您需要将subProjectId保留在ng-repeat范围之外,以便在控制器内部可用,您需要使用$parent anotation将该变量放在控制器范围内而不是ng-repeat

因此,您可以根据viewProject.SubProjectIds轻松过滤subProjectId并在那里显示标题元素。

<强>标记

<h1>{{(viewProject.SubProjectIds| filter: {Id: subProjectId}: true)[0].Name}}</h1>
<ul class="naviPrCatgInfo">
    <li ng-repeat='subProject in viewProject.SubProjectIds' ng-click="$parent.subProjectId = subProject.Id"
       ng-class="{'selected' : subProject.Id === subProjectId}">
        <a ng-class="subProject.Name | trimSpace" ng-href="" ng-click='changeSubProCat(subProject)'>
           {{subProject.Name}} {{subProject.Id}}
        </a>
    </li>
</ul>