AngularJS - how to use ng-required only for active

2019-09-21 16:03发布

  • I have an application where toggle button is, and when clicked, it activates fields for user input.
  • Fields are on one page, button is calling like this:

<span ng-include="'partials/triggers/toggleButton.html'"></span>
<a ng-click="toggle()">
<span class="glyphicon" ng-class="{'glyphicon-ban-circle': t.active, 'glyphicon-ok-circle': !t.active}"></span>
</a>
<div ng-controller="TriggerController" ng-init="init(relay, 'inactiveFor')">
<fieldset class="form-group sentinel-line" ng-disabled="!t.active">
<div class="form-group" bs-has-error>
<input type="text" name="timerEveryMinute" class="form-control" ng-model="t.on.val" ng-pattern="/^(((([1-9])|([1-9][0-9])|([1-9][0-9][0-9])|([1-9][0-9][0-9][0-9]))))$/"/> minutes
<span ng-show="form.timerEveryMinute.$invalid && showInvalids" class="formError">Incorrect value</span>
</div>
<span style="color:#B40404" class="help-block" ng-show="!form.timerEveryMinute.$valid">
Invalid! Must be number with max four digits, without decimals.
<br>Correct: "2" or "23" or "2323" . Incorrect: "2,32" or "23.2" or "232323" .
</span>
<div class="form-group" bs-has-error>
<input type="text" name="timerForMinute" class="form-control" ng-model="t.off.val" ng-pattern="/^(((([1-9])|([1-9][0-9])|([1-9][0-9][0-9])|([1-9][0-9][0-9][0-9]))))$/"/> minutes...
<span ng-show="form.timerForMinute.$invalid && showInvalids" class="formError">Incorrect value</span>
</div>
<span style="color:#B40404" class="help-block" ng-show="!form.timerForMinute.$valid">
Invalid! Must be number with max four digits, without decimals.`
`<br>Correct: "2" or "23" or "2323" . Incorrect: "2,32" or "23.2" or "232323" .
</span>
<span ng-include="'partials/triggers/toggleButton.html'"></span>
</fieldset>
</div>

  • How to make the fields required (non empty) only when they are activated by toggle button? Regex is not working here, it works only if user do some input.

The whole code is here: https://github.com/romanicak/growduino-client/tree/master/src

1条回答
家丑人穷心不美
2楼-- · 2019-09-21 16:36

Use a variable in your controller to track whether the fields are required:

$scope.isRequired = false;

When your button is clicked, toggle that variable

<button ng-click="isRequired = !isRequired">

In your inputs, bind the requirement to that variable:

<input type="text" ng-model="myinput" ng-required="isRequired" />

That's it. It will work even if you don't define the variable in the controller.

Working JSFiddle

查看更多
登录 后发表回答