gpt4 book ai didi

javascript - 在 angular.js 中从 Controller 启用禁用按钮

转载 作者:行者123 更新时间:2023-11-29 21:13:21 25 4
gpt4 key购买 nike

我有一个按钮,需要根据用户是否在 html 页面中输入值来控制它。

我已将模型绑定(bind)到文本字段,并在 $scope 上设置了一个禁用变量,它根据输入字段模型的值启用/禁用。

这是HTML

<!--This button should be disabled if no value is enterd in both the field-->
<input type='button' value='click' ng-disabled='disabled'>
<br>
<input type="text" ng-model="first">
<br>
<input type="text" ng-model='last'>

这是对应的 Angular Controller 。

angular.module('app', []).controller('myController', function($scope) {

$scope.disabled = !$scope.first || !$scope.last;

})

第一次运行,之后不显示基于后面修改的变化。

根据我的理解,angular 使用双向绑定(bind),所以如果我在 View 上修改任何内容,它应该反射(reflect)在 Controller 上,然后 Controller 上发生的任何更改都应该反射(reflect)在 View 上。我在这里做错了什么?

PS:我不想用form
我想避免文本输入字段上的 onChange 事件。

请引用plunk http://plnkr.co/edit/L5wkcpNzMMBZxtcitJwk?p=preview

最佳答案

使用 ng-disabled='!first || !last'.

以下逻辑似乎有效,至少在您的 Plunker 中是这样:

<input type='button' value='click' ng-disabled='!first || !last'>
<br>
<input type="text" ng-model="first">
<br>
<input type="text" ng-model='last'>

作用域变量 $scope.first$scope.last 是双向绑定(bind)到 Controller 的。这意味着输入框中的任何更改都应自动反射(reflect)在这些变量的状态中。但是 disabled 是一个计算量,它会在 Controller 加载时计算一次,但不会在您的代码中再次计算。因此,disabled 似乎始终为 true,即使您已在两个输入框中输入了文本。

Plunker

关于javascript - 在 angular.js 中从 Controller 启用禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com