【问题标题】:Angular - ng-disabled not working after scope changeAngular - ng-disabled 在范围更改后不起作用
【发布时间】:2019-01-14 07:02:53
【问题描述】:

我有一个输入和一个按钮。我希望在输入为空或长度超过 15 个字符时禁用该按钮。

HTML

<input type="text" id="addCustomer" ng-model="customerNumber">
<button id="addSingleCustomerButton" ng-disabled="!isValidSingleInput(customerNumber)" ng-click="addCustomer()"></button>

isValidSingleInput

$scope.isValidSingleInput = function(input) {
    return (input != undefined && input.length > 0 && input.length <= 15);
}

添加客户

$scope.addCustomer = function() {
    $('#addSingleCustomerButton').button('loading');

    // Call service to add customer number to database
    CustomerService.add({}, payload, function(data) {
        $('#addSingleCustomerButton').button('reset');
        $scope.customerNumber = '';
    });
}

addCustomer 函数结束时,通过使用$scope.customerNumber = ''; 设置范围来清除输入字段。

但是,在清除输入后该按钮不会再次被禁用。我在isValidInput 函数中添加了一个日志,其中包含它的结果,它在清除输入后返回false。因此调用了该函数并返回了预期值,但不知何故对按钮的ng-disabled 没有影响。

编辑:添加功能addCustomer

EDIT2: 认为没关系,但问题是由 Bootstrap 的 button.js 引起的。如果我删除 .button('loading').button('reset') 它正在工作。在我看来,这无论如何都应该有效,因为我在按钮之后重置范围。

【问题讨论】:

  • 显示更多代码....因为我已经复制了您的代码并在这里尝试了它的工作正常!
  • 编辑了我的问题
  • 你可以试试这个---> jsfiddle.net/c_Dhananjay/ugchy8ew/17 ?
  • 是的,我当然可以手动实现.button() 功能,但我认为它应该按原样工作......

标签: javascript angularjs


【解决方案1】:

你能检查一下为什么它可能不适合你吗?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.isValidSingleInput = function(input) {
    return (input != undefined && input.length > 0 && input.length <= 15);
	}
    $scope.addCustomer = function(){
    	$scope.customerNumber = '';
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

<input type="text" id="addCustomer" ng-model="customerNumber">
<button id="addSingleCustomerButton" ng-disabled="!isValidSingleInput(customerNumber)" ng-click="addCustomer()">BUTTON</button>

</div>

【讨论】:

  • 我的情况的不同之处在于我有一个异步调用来将客户编号保存在数据库中。然后在回调中清除输入。
猜你喜欢
  • 2018-07-10
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 2015-04-18
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多