【问题标题】:Angularjs - How can it point to all the ng-repeat from on of them by a ng-click?Angularjs - 它如何通过 ng-click 指向它们中的所有 ng-repeat?
【发布时间】:2014-05-01 01:08:42
【问题描述】:

如何从 ng-click 函数中指向其他 ng-repeat 元素? 我想将其他 ng-repeat 元素的 {{nameClass}} 从点击修改为其中的某个人。

HTML:

<li class="{{nameclass}}" ng-repeat="person in people" ng-click="somefunction()"></li>

javascript:

function somefunction(){
     this.nameclass = "some";
     //what to set the other classes???
}

【问题讨论】:

  • 您需要更具体。解释清楚一点。
  • 就是这样...我想修改其他 ng-repeat 元素的 {{nameClass}},从点击到其中的某个人。
  • 所以您希望所有项目在单击其中一个后都具有some 类名?
  • 是的一些类值。

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

您可以在 ng-click 上将要设置的类传入函数中。请参阅此 plunk http://plnkr.co/edit/oXavr7CVTpPfPUZJO0f9?p=preview

【讨论】:

    【解决方案2】:

    您还可以使用ng-class 并设置一些布尔值以在您想要的任何对象上启用给定类。

    在你的控制器中

    $scope.someFunction = function (){
        $scope.active = true;
    }
    $scope.someOtherFunction = function (){
        $scope.loading = true;
    }
    

    在您的 HTML 中

    <li ng-class="{activeClass: active, someOtherClass: loading}" ng-repeat="person in people" ng-click="somefunction()"></li>
    

    它的作用是在“active”为真时将“activeClass”添加到类定义中。我添加了第二个“someOtherClass”来进一步说明这个例子。

    【讨论】:

      【解决方案3】:

      如果您的目标是为所有项目设置 same 类值,那么您应该使用 $scope.nameclass:

      function somefunction(){
          $scope.nameclass = "some";
      }
      

      不同的是,当您使用this.nameclass 时,您设置了当前项目范围的nameclass 属性,而不是所有 项目所属的父范围。当您将其设置为 $scope 对象时,所有 LI 项目都继承 nameclass 而不仅仅是单击一个。

      【讨论】:

      • 是的,我知道,但是如果我想将所有类设置为某个值,并且在“this”ng-repeat 元素的类之后.. 下次我要点击另一个 ng -repeat 元素,保持其旧值之前的元素类。
      • 我为你创建了一个 Plunker:plnkr.co/edit/lzribQXc9E5w6LDTFDwB?p=preview 类 some 有红色文本: .some { color: red;} 当你点击一个项目时全部变成红色。随意修改示例。希望这能帮助我们更好地了解您的需求。
      【解决方案4】:

      我相信这就是您正在寻找的:

      <li ng-class="{true: 'someOther'}[$index!=selectedIndex]" 
          ng-repeat="person in people" ng-click="somefunction($index)">{{person}}</li>
      
      $scope.people = ['Peter','Paul','Mary'];
      $scope.selectedIndex = 0;
      $scope.somefunction = function(index) {
        $scope.selectedIndex=index;
      };
      

      在 Plunker 中:

      http://plnkr.co/edit/2IsD2W3YclUe0Bc5Q93a?

      1. 当您单击一个项目时,该项目的索引被设置为范围上的 selectedIndex 属性。
      2. 索引不等于此 selectedIndex 的所有项目都应用了“someOther”类。

      ng-class中表达式的完整解释:

      https://stackoverflow.com/a/18126926/2331058

      【讨论】:

      • 没有重复元素,独立元素,它允许你同时选择两者。
      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2013-10-02
      • 2015-05-04
      • 1970-01-01
      相关资源
      最近更新 更多