找出几个使用指令/角度的索引

时间:2014-09-27 16:52:27

标签: angularjs angularjs-directive

我写了一个指令,为踢球游戏提供一些可点击的div,看起来像这样:

<span>Team 1</span>
<scoreDisplay>
    <div ng-click="setScore(0)" class="score-item">1</div>
    <div ng-click="setScore(1)" class="score-item">2</div>
    <div ng-click="setScore(2)" class="score-item">3</div>
    <div ng-click="setScore(3)" class="score-item">4</div>
    <div ng-click="setScore(4)" class="score-item">5</div>
    <div ng-click="setScore(5)" class="score-item">6</div>
</scoreDisplay>

<span>Team 2</span>
<scoreDisplay>
    <div ng-click="setScore(0)" class="score-item">1</div>
    <div ng-click="setScore(1)" class="score-item">2</div>
    <div ng-click="setScore(2)" class="score-item">3</div>
    <div ng-click="setScore(3)" class="score-item">4</div>
    <div ng-click="setScore(4)" class="score-item">5</div>
    <div ng-click="setScore(5)" class="score-item">6</div>
</scoreDisplay>

点击一个得分项后,我想得到该指令的索引, 里面的项目,这里是控制器内的scopefunction:

$scope.game = {
    team_1:{name:'Ateam',score:0}
    team_2:{name:'Bteam',score:0}
};
$scope.setScore = function(itemindex, directiveindex){
    $scope.game["team_"+(directiveindex+1)].score = (itemindex+1)

}

任何想法,我如何获得带有角度的指令索引(父元素dom索引)? 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

对代码部分使用ng-repeat指令,如:

    <div ng-click="setScore(0)" class="score-item">1</div>
    <div ng-click="setScore(1)" class="score-item">2</div>
    <div ng-click="setScore(2)" class="score-item">3</div>
    <div ng-click="setScore(3)" class="score-item">4</div>
    <div ng-click="setScore(4)" class="score-item">5</div>
    <div ng-click="setScore(5)" class="score-item">6</div>

您可以在控制器中替换:

$scpe.teams = [...]

在模板中:

<div ng-repeat="team in teams" ng-click="setScore(team.score,$index)" class="score-item">{{team.name}}</div>

您可以对scoreDisplay进行类似的更改

答案 1 :(得分:0)

找到一个带有属性&#34; index&#34;的解决方案:

<scoreDisplay index="1"></scoreDisplay>
<scoreDisplay index="2"></scoreDisplay>

这很好,但我会寻找更好的解决方案 像这样或类似的东西:

angular.element("body scoreDisplay").index($event.target);