Problems with ng-required and ng-disable

1

I have a web application where a person can enter their abilities but if there is a bug that allows them to enter blank skills, then I am trying to use ng-required on input and ng-disable on my button to this does not happen, but it is not working.

View

Itworksasfollows,whenIclicktheaddbuttonmyControllergeneratesanewinputandthenjustwritetheskillandthensave.

ViewCode

<divclass="panel-body">
  <div class="row">
    <div class="col-sm-6">
      <div class="form-group" ng-repeat="item in habilidades">
        <div class="input-group">
          <span class="input-group-btn">
            <button class="btn btn-default" type="button" ng-click="removeHabilidade(item)">
              <i class="fa fa-trash-o"></i>
            </button>
          </span>
          <form name="form">
          <input class="form-control" type="text" ng-required="true" ng-model="item.nome">
        </form>
        </div>
      </div>

      <button type="button" class="btn btn-link" ng-click="addHabilidade()">
        <i class="fa fa-plus"></i>
        Adicionar
      </button>
    </div>
  </div>
</div>

Function code addHabilidade

$scope.addHabilidade = function() {
  $scope.habilidades.push({ nome: '' });
};

So far so good, the problem happens when I put ng-disable on the Save button.

Save button

<div class="panel-footer">
  <button class="btn btn-default" ng-click="salvarHabilidades()" ng-show="!savingHabilidades" ng-disabled="form.$invalid">
    <i class="fa fa-save"></i>
    Salvar
  </button>

It is as if the value of ng-required was not being passed to the save button, only getting in div of inputs .

It should be some problem with scope or something like that, because if I put ng-required="form.$invalid" on the delete button works, they are disabled.

    
asked by anonymous 03.03.2016 / 20:37

1 answer

2

The solution you are looking at involves the correct use of the ngForm directive.

It is just for you to isolate the scope of each form and disable the save button for each input individually.

For example in the code below:

<div ng-repeat="item in habilidades">
    <ng-form name="itemForm">
          <input type="text" name="nomeItem" ng-model="item.nome" required>
          <button ng-disabled="[CONDIÇÃO PARA DESABILITAR]">
              Salvar
          </button>
    <ng-form>
</div>

Where is the condition to disable you can use several expressions, such as:

!itemForm.$valid
itemForm.$invalid

Where itemForm is the name property of ng-form , that is, you check all the validations of all the inputs of the form (in this case, in particular, only > required of a input ).

Or you can check the validity of a specific input like this:

!itemForm.nomeItem.$valid
itemForm.nomeItem.$invalid

Where nomeItem is the name property of the input within the itemForm form.

If there is still any doubt, you can search for form validations on these links:

link
link

    
15.03.2016 / 14:23