在AngularJS中为变量分配别名

时间:2015-12-10 20:16:17

标签: angularjs

所以,如果我有这个HTML:

<ul>
    <li ng-repeat="person in course.people">

        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].gradeAverage"></span>
        </div>
        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].bestGrade"></span>
        </div>
        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].worstGrade"></span>
        </div>
        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].numberOfClasses"></span>
        </div>
        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].year"></span>
        </div>
        <div>
            <span bg-bind="schools[schools.currentSchool][person.id].timesFlunked"></span>
        </div>

    </li>
</ul>

我需要多次访问schools[schools.currentSchool][person.id],这会让代码在一段时间后变得非常混乱。有没有办法把ng-alias="x=schools[schools.currentSchool][person.id]"之类的东西放在某处?这样我就可以在需要的地方使用x.gradeAverage。或者其他一些使HTML看起来不那么混乱的方法呢?

顺便说一句,示例HTML完全是随意的,我只是做了些什么,但我希望你理解我在问什么。

2 个答案:

答案 0 :(得分:1)

如果要输出person对象的所有成员,可以迭代这样的属性:

<li ng-repeat="person in course.people">
    <div ng-repeat="(key,value) in schools[schools.currentSchool][person.id]">
    <span ng-bind="value"></span>
    </div>
</li>

Plunker示例:http://plnkr.co/edit/c9psDfNkh5LGR0eVjIHg?p=preview

答案 1 :(得分:0)

在您的控制器中,您可以为currentSchool设置范围变量,并将其设置为currentSchool[person.id]。例如:

//controller
$scope.currentSchool = $scope.schools[$scope.schools.currentSchool];

//HTML
<li ng-repeat="person in course.people">
    <div>
        <span ng-bind="currentSchool[person.id].gradeAverage"></span>
    </div>
    <div>
        <span ng-bind="currentSchool[person.id].bestGrade"></span>
    </div>
    ...
</li>

这会缩短一点。还有,schools.currentSchool === schools[schools.currentSchool]?如果是这种情况,那么你可以进一步缩短它。无论哪种方式,数据结构似乎有点混乱。