将类添加到angularjs列表中的当前元素

时间:2016-09-06 07:24:12

标签: angularjs

我有一个列表显示在表格结构中,我给出了每个列表项的复选框以供选择。但我想在单击复选框时选择当前元素。我尝试了ng-class的东西,但是它点击了一个复选框就选择了所有列表。以下是我的代码,请检查。

list.html

<div class="surveyList" ng-repeat="survey in allSurveys |  filter:global.search">
                        <span class="checkbox" ng-click="Click()" ng-class="checked"></span>
                        <div class="toogleSurvey row" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
                            <div class="col-xs-5 col-sm-2  col-md-3">{{survey.SurveyName}}</div>
                            <div class="col-sm-3  col-md-4 hidden-xs">{{survey.Date | date:'dd/mm/yyyy'}}</div>

controller.js

$rootScope.Click = function(){
  $rootScope.surveySelected = !$rootScope.surveySelected;
  if($rootScope.surveySelected){
    $rootScope.checked = 'checked';
  }else{
    $rootScope.checked = '';
  }
};

在此单击一个复选框后,选中&#39; class被添加到ng-repeat中的所有元素中。使用jquery,我们可以使用&#34;这个&#34;关键字,我们可以遍历DOM。那么如何在angularjs中做到这一点?

以下是点击

之前和之后工作的快照

beforeclick enter image description here

afterclick enter image description here

点击一个ckeckbox

后,所有列表中都会添加此已检查的类

根据检查状态显示其他元素。

<强烈> header.html中

<div class="navbar-header col-lg-3 col-md-6 col-sm-3 col-xs-6" ng-show="surveySelected">
                <a class="glyphicon glyphicon-arrow-left col-xs-2" ng-click="" id="backButton"></a>
                <span class="moduleTitle">Back</span>
          </div>

修改了list.html

<div class="surveyList" ng-repeat="survey in allSurveys |  filter:global.search">
                        <span class="checkbox" ng-click="surveySelected=!surveySelected" ng-class="{'checked':surveySelected}"></span>
                        <div class="toogleSurvey row" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
                            <div class="col-xs-5 col-sm-2  col-md-3">{{survey.SurveyName}}</div>...

1 个答案:

答案 0 :(得分:0)

你走了:

<div class="surveyList" ng-repeat="survey in allSurveys |  filter:global.search">
    <span class="checkbox" ng-click="survey.checked=!survey.checked" ng-class="{'checked':survey.checked}"></span>
        <div class="toogleSurvey row" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
            <div class="col-xs-5 col-sm-2  col-md-3">{{survey.SurveyName}}</div>
            <div class="col-sm-3  col-md-4 hidden-xs">{{survey.Date | date:'dd/mm/yyyy'}}</div>
            ...

只需点击设置survey.checked并根据它设置类:ng-class="{'checked':survey.checked}"

P.S。从来没有像这样使用$ rootScope。 :)