我有一个100按钮,点击每个按钮显示其相应的炸弹盒,用javascript和angular

时间:2016-09-06 09:06:49

标签: javascript angularjs

一个对应于提示框的按钮,每个框都是不同的shell;虽然实现了所需的功能,但是我的代码太复杂了,并没有简单的方法。我能怎么做?这是我的代码

<--html button-->
<a href="" ng-click="showRulePop(1)">button1</a>
<a href="" ng-click="showRulePop(2)">button2</a>
  ...
<a href="" ng-click="showRulePop(100)">button100</a>

<--html pop box-->
<div class="note1" style="display:none;">
    <img class="title-css" src="note1.png">   
    <p class="one">note1</p>       
</div>
...
<div class="note100" style="display:none;">
    <img class="title-css" src="note100.png">   
    <p class="one">note100</p>       
</div>

<--angular js-->
$scope.showRulePop = function(index) { 
    for(var i=1;i<=8;i++) {
        $('.note'+i).hide();          
    }
    $('.note'+index).show();
};

1 个答案:

答案 0 :(得分:0)

首先,不要使用jQuery,除非你在angular jQuery的指令级别没有任何关系。

首先让我们使用简单的ng-repeat来删除链接部分:

<--html button-->
<div ng-repeat="button in buttons"> 
    <a href="" ng-click="showRulePop(i)">{{button.label[i]}}</a>
</div>

// JS in the controller
$scope.buttons = [{
    label:'button1'
},{label:'button2'}];

正如你所看到我在javascript中声明所有按钮,我只是循环它。

现在,“bombox”或其他任何内容让它成为一个简单的模板:

<div class="{{currentnote.class}}" ng-if="currentNote">
    <img class="title-css" src="{{currentNote.img}}">   
    <p class="one">{{currentNote.content}}</p>       
</div>

//并且在没有选择按钮的情况下首先使用ng-repeat作为八个

<!-- show 1 to 8 if note current note selected -->
<div ng-repeat="button in buttons1To8" ng-if="!currentNote">
     <div class="{{button.note.class}}">
        <img class="title-css" src="{{button.note.img}}">   
        <p class="one">{{button.note.content}}</p>       
    </div>
</div>

// JS

$scope.buttons = [{
    label:'button1'
    note:{class:'note1', img:'note1.png', content:'note1'//assuming no HTML or you' ll need something more
}},{label:'button2', note:{...}}, ...];

$scope.showRulePop = function(index){
    $scope.currentNote = $scope.buttons[index].note;
}

$scope.buttons1To8 = $scope.buttons.slice(0, 8);//0 to 7 in fact

这就是全部,不需要jQuery。