单击ng-repeat时如何禁用按钮?

时间:2018-04-16 09:33:22

标签: angularjs

我想在点击时禁用该按钮然后如果点击到另一个按钮,则前一个禁用按钮将处于活动状态,然后当前按钮将被禁用,依此类推等等

HTML

<div ng-controller="ModalDemoCtrl">
    <button ng-repeat="item in items track by $index" ng-click="test($index);" ng-disabled="dis[$index]">
       {{item.Name}}
    </button>
</div>

CODE

$scope.items = [{ Name: 'apple' }, { Name: 'banana' }, { Name: 'carrot' }, { Name: 'drumstick' }, { Name: 'egg' }];
$scope.test = function(i){
  $scope.dis[i] = true;
}

此代码会给我这个错误

TypeError: Cannot set property '2' of undefined
    at copywriter-angular.js?ver=1.2:1234
    at angular.min.js?ver=4.8:134
    at m.$digest (angular.min.js?ver=4.8:145)
    at m.$apply (angular.min.js?ver=4.8:149)
    at l (angular.min.js?ver=4.8:102)
    at XMLHttpRequest.A.onload (angular.min.js?ver=4.8:107) "Possibly unhandled rejection: {}"

2 个答案:

答案 0 :(得分:3)

只需定义$scope.dis以上test功能。

$scope.dis= [];
$scope.test = function(i){
  $scope.dis[i] = true;
}

答案 1 :(得分:1)

我认为你的逻辑错误。您需要展开具有disabled属性的对象数组,而不是使用单独的数组来禁用按钮。 ng-disabled="item.disabled"

但是如果你想要一个单独的数组,这里就是你如何初始化它,因为否则它是空的,因此你无法访问dis[index]来禁用该按钮。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.items = [{
    Name: 'apple'
  }, {
    Name: 'banana'
  }, {
    Name: 'carrot'
  }, {
    Name: 'drumstick'
  }, {
    Name: 'egg'
  }];
  $scope.dis = $scope.items.map((_) => {
    return false;
  });
  $scope.test = function(i) {
    $scope.dis[i] = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-repeat="item in items track by $index" ng-click="test($index);" ng-disabled="dis[$index]">
    {{item.Name}}
  </button>
</div>

这是您应该使用的解决方案。这次对象有一个你可以轻松访问的附加属性。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.items = [{
    Name: 'apple',
    disabled: false
  }, {
    Name: 'banana',
    disabled: false
  }, {
    Name: 'carrot',
    disabled: false
  }, {
    Name: 'drumstick',
    disabled: false
  }, {
    Name: 'egg',
    disabled: false
  }];
  $scope.test = function(i) {
    $scope.items[i].disabled = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-repeat="item in items track by $index" ng-click="test($index);" ng-disabled="item.disabled">
    {{item.Name}}
  </button>
</div>