2

I have an AngularJs form where I want to know the amount of hours worked. If the amount is 0, I want to enable an extra question for the reason of not working.

<label>How many hours did you work?</label> <input ng-model="hours" type="number" placeholder="8" /> <label ng-class="{'disabled-label': ifHoursZero}">Why didn't you work at all?</label> <input ng-disabled="ifHoursZero" ng-model="reason" type="text" /> 

What is the elegant Angular way to toggle CSS and input fields with ifHoursZero if the hours value is 0. Can this be done directly with the hours variable with some pattern?

1
  • you could use ng-show and ng-hideCommentedMay 4, 2015 at 13:50

2 Answers 2

2

Make ifHoursZero a function that returns a boolean and call it like ng-disabled="ifHoursZero()"

For example:

function ifHoursZero() { return $scope.hours === 0; } 

See jsBin

    2

    You should be able to do this without having to add a function to the controller:

    <label>How many hours did you work?</label> <input ng-model="hours" type="number" placeholder="8" /> <div ng-show="hours === 0"> <label>Why didn't you work at all?</label> <input ng-model="reason" type="text" /> </div> 
    3
    • Does the reason variable bind at all if the ng-show hides it? And what if it shows it (by entering 0) and then hides it again (by entering >0)? Does it affect to its default scope values?
      – Pekka
      CommentedMay 4, 2015 at 14:10
    • @Pekka it should be there hidden or not.. (enter 0 hours, type something, change hours to 1, reason should still be there) So in your controller you might want to check hours depending on what you're doing with reason.CommentedMay 4, 2015 at 14:12
    • what you have mentioned is about showing and hiding input field and not enabling or disabling it !CommentedMay 7, 2019 at 15:10

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.