Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling angular $setValidity in controller

Tags:

angularjs

I have an input field and a button where a user enters an address to be geolocalized. It's part of a bigger form but I wish the validity of that field to be handled when they presss the "Map it" button instead of the final form submit. How can I set this field as invalid? Calling $setValidity results in an undefined/not a function error.

Form bit:

<form name="myForm">
  <input type="text" name="addy" ng-model="addy">
  <a ng-click="geoCode()">Map it!</a>
  <span class="error" ng-hide="myForm.addy.$invalid">Bad field</span>
  ....
</form>

Controller:

$scope.addy = null

// This is a more complex async function trimmed down to essentials
$scope.geoCode = function() {
  $scope.addy.$setValidity('unique', false);
});

I'd also like that field to only be checked once. So if they enter an address and do not press the Map it button then it will be checked on submit, but if they did press the Map button and field is valid then it will not run through the async function again. Suggestions as to how to best handle this?

like image 702
cyberwombat Avatar asked Jun 11 '15 17:06

cyberwombat


1 Answers

If you would like to set the validity of your input field within your controller you could simply pass along the form and access your input just as you would in your markup. I have also included a working example:

var app = angular.module('form-example', []);

app.controller('FormCtrl', function($scope) {
  var vm = this;

  vm.geoCode = function(form) {
    form.addy.$setValidity('unique', false);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<form ng-app="form-example" name="myForm" ng-controller="FormCtrl as vm">
  <input type="text" name="addy" ng-model="vm.addy">
  <a ng-click="vm.geoCode(myForm)">Map it!</a>
  <span class="error" ng-hide="myForm.addy.$invalid">Bad field</span>
</form>
like image 62
LordTribual Avatar answered Sep 26 '22 02:09

LordTribual