Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - ng-disabled not working after scope change

I have an input and a button. I want the button to be disabled when the input is empty or is more than 15 characters long.

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

addCustomer

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

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

At the end of the addCustomer function the input field is cleared by setting the scope with $scope.customerNumber = '';.

However, the button is not disabled again after clearing the input. I added a log to the isValidInput function with the result of it and it returns false after clearing the input. So the function is called and it returns the expected value, but it somehow has no effect on the button's ng-disabled.

EDIT: Added function addCustomer

EDIT2: Didn't think it would matter, but the problem is caused by Bootstrap's button.js. If I remove the .button('loading') and .button('reset') it's working. In my eyes this should work anyways because I'm resetting the scope after the button.

like image 652
Thomas Göhringer Avatar asked Feb 02 '26 20:02

Thomas Göhringer


1 Answers

can you check to see why it might not be working for you?

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>
like image 101
Akber Iqbal Avatar answered Feb 05 '26 09:02

Akber Iqbal