简体   繁体   中英

Set button active when form is filled (Angular)

I have the following controller and directive:

app.controller('controlFormulario', ['$scope', function($scope) {
  var cf = this;
  cf.formulario = [];
  cf.formulario.fecha = new Date();

  if(cf.formulario.texto != null && cf.formulario.titulo != null){
    this.formulario.isDisabled = false;
  }
}]);

app.directive('formulario', [function() {
  return {
    restrict: 'E', // C: class, E: element, M: comments, A: attributes
    templateUrl: 'modules/formulario.html',

  };
}]);

And this is the DOM element of the button, the one I want to enable when there is some text in the title and text fields:

<div class="form-group" ng-init="formCtrl.formulario.isDisabled = true">
  <button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit" disabled={{formCtrl.formulario.isDisabled}}>
  Enviar
  </button>
</div>

Currently, the controller function that enables the button, isn't working at all. I've got it instantiated in the main div of the formulary, and it's working properly with the data binding, but it's somehow not enabling the button.

What am I doing wrong?

Use ng-disabled instead of the disabled attribute.

<button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit" ng-disabled="formCtrl.formulario.isDisabled">

From the linked documentation:

A special directive is necessary because we cannot use interpolation inside the disabled attribute.

Also, use $scope to expose your data to the view, not this . this refers to the controller, not to the $scope that the view can see.

使用ng-disabled代替disabled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM