Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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.


2 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/

like image 87
jlmcdonald Avatar answered Sep 13 '25 01:09

jlmcdonald


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>
like image 20
zs2020 Avatar answered Sep 13 '25 01:09

zs2020