angular ng repeat禁用除第一项以外的所有项目

时间:2016-09-01 09:36:52

标签: javascript jquery angularjs

我有一个项目列表。每个项目都在div中。我想只显示第一项启用,其他显示已禁用。

AngularJs

angular.module('example', [])
.controller('myCtrl', function Ctrl($scope) {
    $scope.items = [1,2,3];
});

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="example" ng-controller="myCtrl">
   <div ng-repeat="item in items">{{item}}</div>
</div>

5 个答案:

答案 0 :(得分:8)

只需使用$first属性:

<div ng-app="example" ng-controller="myCtrl">
     <div ng-repeat="item in items" ng-disabled="!$first">{{item}}</div>
 </div>

注意:ng-disabled适用于表单元素。有关详细信息,请参阅documentation

答案 1 :(得分:3)

你可以先使用$。

&#13;
&#13;
 angular.module('example', [])
    .controller('myCtrl', function Ctrl($scope) {
    $scope.items = [1,2,3];
      });
&#13;
    

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

    <div ng-app="example" ng-controller="myCtrl">
         <div ng-repeat="item in items"><span ng-if="$first">{{item}}</span>
<span ng-if="!$first">do whatever you want with this item {{item}} </span>
</div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:3)

试试这个代码段。

angular.module('example', [])
    .controller('myCtrl', function Ctrl($scope) {
      $scope.items = [1,2,3];
});
.disable {
  color: #ccc;  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="example" ng-controller="myCtrl">
  <b>First way</b>
  <div ng-repeat="item in items track by $index">
    <input ng-disabled="$index != '0'" type="text" value="do whatever you want with this item {{item}}"/>
  </div>
  <br/>
  <b>Second way</b>
  <div ng-repeat="item in items">
    <input ng-disabled="!$first" type="text" value="do whatever you want with this item {{item}}"/>
  </div>
  <br/>
  <b>Third way</b>
  <div ng-repeat="item in items">
    <span ng-class="{'disable': !$first}">do whatever you want with this item {{item}}</span>
  </div>
</div>

答案 3 :(得分:2)

<div ng-app="example" ng-controller="myCtrl">
     <div ng-repeat="item in items" ng-class='{disable:!$first}' >{{item}}</div>
</div>

答案 4 :(得分:1)

使用禁用类我们只能应用禁用css,如果有人确实从控制台更改了然后它会中断我所做的如下

<div ng-app="example" ng-controller="myCtrl">
    <div ng-repeat="item in items" ng-class="{'disabled-me': !($index==0)}">
    <span ng-click="($index!=0) ? false : xyx(item)">{{item}}</span></div>
</div>

在css中

.disabled-me,.disabled-me span{color: #777 !important;cursor: default;}