1

My form is very simple. Think of it as having 1 field and one submit button. The validation I want is also quite simple, if the 1 field is empty, then the submit button will be disabled. If not, the submit button will work. I am trying to do this dynamically using AngularJs and not quite sure what I am missing.

Although I am using Django-forms, my form renders in Html like this:

<div ng-app="myApp" ng-controller="searchController">
    <form method='POST' action='' class="form-with-blue-labels" name="searchForm">
        {% csrf_token %}
        <input class="textinput textInput form-control" id="id_professor_name" maxlength="255" name="professor_name" placeholder="Search for a professor" required="required" type="text">
        <input ng-disabled="disabled_bool" type="submit" class="btn btn-primary" value="Search" />
    </form>
</div>

And my angular file looks like this:

angular.module('myApp', [])

.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('{$');
  $interpolateProvider.endSymbol('$}');
})

.controller('searchController', [
  '$scope', function($scope) {
    var search_target = angular.element('#id_professor_name');
    if (search_target == ''){
      $scope.disabled_bool = true;
    }
  }
])

Note: Since I am using Django and Angular together in a non-restful way, I changed the angular tags to be {$$}, while Django tags are {{}}.

Any help is appreciated!

EDIT

I have tried this now, and still can't get it to work :/

<div ng-app="myApp" ng-controller="searchController">
    <form method='POST' action='' class="form-with-blue-labels" name="searchForm">
        {% csrf_token %}
        <input ng-change="change()" class="textinput textInput form-control" id="id_professor_name" maxlength="255" name="professor_name" placeholder="Search for a professor" required="required" type="text">
        <input ng-disabled="disable_button" type="submit" class="btn btn-primary" value="Search" />
    </form>
</div>

using this function

angular.module('myApp', [])

.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('{$');
  $interpolateProvider.endSymbol('$}');
})

.controller('searchController', [
  '$scope', function($scope){
    $scope.change = function(){
      if (angular.element('#id_professor_name').length == 0) {
        $scope.disable_button = true;
      }
      else {
        $scope.disable_button = false;
      }
    };
  }
])
darkhorse
  • 8,192
  • 21
  • 72
  • 148

1 Answers1

0

As suggested here, you need to use ng-disabled="searchForm.$invalid" as you have already set name to required.

Community
  • 1
  • 1
Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
  • This does not work either weirdly. I even added ng-required='required' to my input, but even then it did not work. – darkhorse Feb 23 '16 at 16:59