1

if to disable a button based on condition. i am getting empty object initially so i need to disable the button below is my code:

<button class="btn-reg btn btn-primary" title="Create Book from Collection"
        ng-click="scenariosViewAll.saveBookData();" 
        ng-disabled="scenariosViewAll.collectionBookObject == {}">Create Book from Collection
</button>

vm.collectionBookObject in controller

if i console the object i am getting: {} so i am using above condition.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Sudhir MN
  • 125
  • 8
  • 1
    see https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object – Turo Dec 24 '17 at 12:46
  • Consider using form controls to enable/disable the create button. For more information, see [AngularJS Developer Guide - Forms - Binding to form and control state](https://docs.angularjs.org/guide/forms#binding-to-form-and-control-state). And [AngularJS `
    ` Directive API Reference - Submitting a form and preventing the default action](https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action).
    – georgeawg Dec 24 '17 at 20:06
  • You can try until object 'null': ng-disabled="scenariosViewAll.collectionBookObject == {} || true" – Hanif Dec 24 '17 at 20:06

1 Answers1

0

scenariosViewAll.collectionBookObject == {} will always be false because objects in javascipt are compared by reference.

You need to play it smarter on this.

your object scenariosViewAll.collectionBookObject could be initialised to a null value. That way, your condition would simply be ng-disabled="!scenariosViewAll.collectionBookObject".

If for any reason, you cannot initialize your object to a null value, you can check if there is a key in your object : ng-disabled="!Object.keys(scenariosViewAll.collectionBookObject).length"

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
  • ng-disabled="!Object.keys(scenariosViewAll.collectionBookObject).length is disabling but enable is not happening if i get data – Sudhir MN Dec 24 '17 at 13:04
  • you should try using immutable objects. If you just add properties into your object, angular won't know you updated the object, and won't trigger a digest on the view. If you need more information, can you add the code where you initialize and update your object into your question? – Deblaton Jean-Philippe Dec 24 '17 at 13:17