1

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

mding5692
  • 806
  • 1
  • 10
  • 34

2 Answers2

1

You could work with ng-click on the link instead and handle the validation in the controller.

  $scope.go = function() {
      if (!$scope.selectedItem) {
        alert("You have to select")
      } else {
        window.location.href = $scope.selectedItem.id;
      }
  }

And in the view:

  <a ng-click="go()">Let's go</a>

Here's the updated code http://plnkr.co/edit/CLwFsNIUgt7PPRA3f4HA?p=preview

Julia Will
  • 616
  • 3
  • 8
1

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

Claies
  • 22,124
  • 4
  • 53
  • 77
  • Sorry about not clarifying this, but I didn't want the Select Bank span element to appear until "Let's Go" has been pressed. – mding5692 Jul 22 '15 at 15:08
  • wait, you want the href to be there and clickable even if it doesn't have a valid target in it? and don't want the user to know their target isn't valid until they try to click it? – Claies Jul 22 '15 at 15:09
  • did you happen to see the update I just made? are you sure that that doesn't make more sense to the users? – Claies Jul 22 '15 at 15:10
  • Thanks, that would make sense – mding5692 Jul 22 '15 at 15:15