Pankaj Pankaj - 4 months ago 27
Javascript Question

Enable disable button from controller in angular.js

I have a button which needs to be controlled on the basis of if the user has entered the values in the html page.

I have binded model to the text field and set a disabled variable on the $scope, which is enabled/disabled on the value of the input field model.

Here is the HTML

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

And here is the correponding angular controller.

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

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


It runs for the first time, but then don't show changes on the basis of later modifications.

As per my understanding angular uses two way binding, so if I am modifying anything on the view it should be reflected on the controller, and then anything changed on the controller should be reflected on the view.
What wrong I am doing here?

PS: I dont want to use form

I want to avoid the onChange event on the text input field.

Please refer the plunk


Use ng-disabled='!first || !last'.

The following logic seems to work, at least in your Plunker:

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

It is true that the scoped variable $scope.first and $scope.last are two-way bound to the controller. This means that any change in the input boxes should automatically reflect in the state of these variables. But disabled is a computed quantity, and this is calculated once, at the time the controller loads, but not again in your code. Hence, disabled appears to always be true, even after you have entered text into both input boxes.