为什么 ng-disabled 在按钮上不起作用?

Why is ng-disabled not working on button?

我的 Plunkr:http://plnkr.co/edit/4MkenJPczFbxy5aoillL?p=preview

<body ng-controller="mainCtrl as main">

<h1>Hello Plunker!</h1>
<p>Button should not be disabled:</p>

<div ng-init="main.btnDisabled = false">
    <button ng-model="main.my_button"
         ng-class="{ 'btn-success' : !tc.switching, 'btn-disabled' : tc.switching }"
         disabled="main.btnDisabled"
         type="button"
         class="btn btn-info btn-sm switch-btn">My Button</button>  
</div>

Angular

angular.module('app').controller('mainCtrl', function($scope) {
  vm = this;
  vm.btnDisabled = false;
});

我找到了 this answer here,但它在我的示例中不起作用。

该按钮被禁用,因为有 disabled 属性。这足以让浏览器知道该元素必须处于非活动状态。 disabled attribute 的值无关紧要,它可以是任何值。

这正是 Angular 提供 ngDisabled 指令的原因,该指令在表达式求值为 true 时添加 disabled 属性,并在 false 时删除].

在你的情况下你应该使用

<button ng-model="main.my_button"
        ng-class="{ 'btn-success' : !tc.switching, 'btn-disabled' : tc.switching }"
        ng-disabled="main.btnDisabled"
        type="button"
        class="btn btn-info btn-sm switch-btn">My Button</button>  

我在这里看到了一些问题。

首先,将 disabled 更改为 ng-disabled。

其次,当你点击按钮时什么都不会change/happen。不要将该功能放入您的 ng-class,而是使用 ng-click 之类的东西来更改状态。

这不会导致您的问题,但请确保在将 $scope 传递到您的控制器函数之前包含它。

说到 $scope,如果你把一些东西放在范围上而不是使用控制器别名,那么 plunker 会更容易阅读。没问题,它可能会帮助您和其他人调试您的代码。