在ng-click上切换ng-repeat中的其他元素

时间:2016-03-29 06:16:18

标签: javascript angularjs

我尝试使用ng-class和ng-click来应用类,这对于所选元素工作正常,但是如何在其他元素中切换此类?
改进说明
当前行为
点击elelement,应用课程。
Clik在另一个元素上,这个元素也应用了类 期望的行为
单击元素,应用类。
其他元素 - 类被删除。

<div ng-repeat="element in ngModel | orderBy:'Field_Order'" class='elementForm' ng-hide="element.IsDeleted">
    <div layout="row" style="width:100%" class="container" ng-mouseover="hovering=true" ng-mouseleave="hovering=false" flex ng-click="selected = !selected">
        <div class="hover-space" ng-class="{'hoveredFormElement':hovering, 'selected':selected}" flex="2" ></div>
        ....
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

问题是,selected位于隔离的范围内,不会被其他项共享。

使用索引的一个简单解决方案是

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.selected = -1;
  $scope.ngModel = [{
    i: 1
  }, {
    i: 2
  }, {
    i: 3
  }, {
    i: 4
  }];
})
.hoveredFormElement {
  color: green;
}
.selected {
  background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app">
  <div ng-controller="AppController">
    {{selected}}
    <div ng-repeat="element in ngModel | orderBy:'Field_Order'" class='elementForm' ng-hide="element.IsDeleted">
      <div layout="row" style="width:100%" class="container" ng-mouseover="hovering=true" ng-mouseleave="hovering=false" flex ng-click="$parent.selected = $parent.selected == $index ? -1 : $index">
        <div class="hover-space" ng-class="{'hoveredFormElement':hovering, 'selected':selected == $index}" flex="2">{{element}}</div>
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:1)

在控制器范围内维护标志并在ng-class

上使用它
$scope.selected = { index: undefined };

<强>标记

<div ng-repeat="element in ngModel | orderBy:'Field_Order'" class='elementForm' ng-hide="element.IsDeleted">
    <div layout="row" style="width:100%" class="container" 
      ng-mouseover="hovering = true" 
      ng-mouseleave="hovering = false" 
      flex ng-click="selected.index = !selected">
        <div class="hover-space" 
         ng-class="{'hoveredFormElement':hovering , 'selected':selected.index }" flex="2" ></div>
        ....
    </div>
</div>