Home » Angularjs » How can I disable a button in AngularJS if there are elements in an array?

How can I disable a button in AngularJS if there are elements in an array?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have an object: model.data

How can I disable a button if this object has an array of questions and if that array has more than one element?

I did try:

data-ng-disabled="model.questions.length > 0"

But this does not seem to work at all.

Answers:

EDIT: Modifying answer in response to posts and comments

What about:

data-ng-disabled="checkQuestions()"

And then in your controller:

$scope.checkQuestions = function() {
 if (model.questions.length > 1) { // your question said "more than one element"
   return true;
  }
  else {
   return false;
  }
};

What it really comes down to is that there are multiple ways to accomplish this task; an expression, a function, a bound variable (as demonstrated by the various responses here). If none of them are working, the problem might lie in your model instead. If you could clear up some inconsistencies (see my comments about asking for the structure of your model… also, are you interested in it disabling if there’s anything in the array, or only if there is more than one thing in the array?), it will help figure this out.

Here’s a fiddle that shows all three approaches; you’ll see that they all work. Compare your controller to the fiddle and see if it comes together.

http://jsfiddle.net/jlmcdonald/P8qjR/3/

Questions:
Answers:

You definitely can use an expression instead of a function. But you may check if the array is undefined.

<button ng-disabled="model.questions != undefined && model.questions.length > 0"></button>

Questions:
Answers:

I couldn’t get @zsong answer to work and I didn’t want to create a function just to return an array length, so I got it working by creating another scope variable which returned the array.length.

$scope.modelQuestionsLength = $scope.model.questions.length;

I could then do

<button ng-disabled="modelQuestionsLength > 0"></button>

Questions:
Answers:

Create a model then set its default value to false. Then change its value to true, if your array length is not empty. Followed with binding the model to the button’s ng-disabled attribute.

Questions:
Answers:

I couldn’t get the undefined way to work, so if anyone else is having trouble, this worked for me:

<input ng-disabled="fieldsPermittedForEdit.indexOf('postDate') < 0">

In this example, I am disabling the field unless postDate exists in the fieldsPermittedForEdit array.