javascripthtmlangularjsvalidationangularjs-ng-href

Angularjs error validation for dropdown/select redirect with ng-href


I'm currently using angularjs's ng-href and a select html element with ng-model where I am using ng-href to link to the "selectedItem" (from ng-model). I was unable to validate or provide an error when nothing was chosen and was wondering how I would do this. Also my ng-href works, I think it just doesn't have the same functionality on Plunker.

Heres my html code:

 <form name="linkForm" ng-controller="MainCtrl">
  <select name="link" ng-model="selectedItem" 
      ng-options="item as item.name for item in items"></select>
      <option value=""></option>  
      <span class="error" ng-show="linkForm.link.$dirty && linkForm.link.$invalid">Please select a website</span>    
  <a ng-href="{{selectedItem.id}}">Let's go</a>
 </form>

Heres my angularjs code

var app = angular.module('angularjs-starter', []);

 app.controller('MainCtrl', function($scope) {
 $scope.items = [
{ id: 'http://www.google.com', name: 'Google'},
{ id: 'http://www.gmail.com', name: 'Gmail'}];
  });

Heres my demo: http://plnkr.co/edit/c9iiLP6spvQK8jYdmYhD?p=preview


Solution

  • You only need to add required to the select in order to make an option necessary for validation. However, you would also need to remove the check for bankLoginForm.bankLogin.$dirty, since it won't be dirty until the user modifies the dropdown. To make the href disappear when the dropdown is invalid, you can add the opposite check on it.

    <select name="bankLogin" ng-model="selectedItem" 
              ng-options="item as item.name for item in items" required>
              <option value=""></option>  </select>
                  <span ng-show="bankLoginForm.bankLogin.$invalid">Select bank</span>
        <a ng-href="{{selectedItem.id}}" ng-show="!bankLoginForm.bankLogin.$invalid">Let's go</a>
    

    http://plnkr.co/edit/JFvvXslCZf9CnHCB0zRT?p=preview