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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29176192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:10:17  来源:igfitidea点击:

Why is ng-disabled not working on button?

javascriptangularjsangularjs-directiveangularjs-scope

提问by Leon Gaban

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

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

enter image description here

在此处输入图片说明

<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;
});

I found this answer here, but it didn't work in my example.

我在这里找到了这个答案,但它在我的例子中不起作用。

回答by dfsq

The button is disabled because there is disabledattribute. This is enough for browser to know that element must be inactive. The value for disabled attributedoesn't matter, it can be anything.

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

This is exactly the reason why Angular provides ngDisableddirective, which adds disabledattibute when expression evaluates to true, and removes when it's false.

这正是 Angular 提供ngDisabled指令的原因,它disabled在表达式计算为 时添加属性true,并在表达式为时删除false

In your case you should use

在你的情况下,你应该使用

<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>  

回答by Daniel Jamrozik

There are a few problems that I see here.

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

First, change disabled to ng-disabled.

首先,将禁用更改为 ng-禁用。

Second, when you click the button nothing will change/happen. Instead of putting that functionality into your ng-class, use something like ng-click to change the state.

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

This isn't contributing to your problem but make sure that you include $scope before passing it into your controller function.

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

Speaking of $scope, the plunker would be a bit easier to read if you put something on the scope instead of using a controller alias. No problem with that, it just might help you and other people debug your code.

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