Angularjs用ng-href对dropdown/select redirect进行错误验证

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

本文关键字:redirect 错误 验证 select ng-href dropdown Angularjs      更新时间:2023-09-26

我目前使用angularjs的ng-href和一个带有ng-model的select html元素,其中我使用ng-href链接到"selectedItem"(来自ng-model)。当没有选择任何内容时,我无法验证或提供错误,并且想知道如何做到这一点。我的ng-href也可以工作,我认为它在Plunker上没有相同的功能。

这是我的html代码:
 <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>

这是我的angularjs代码

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'}];
  });
下面是我的演示:http://plnkr.co/edit/c9iiLP6spvQK8jYdmYhD?p=preview

您只需要将required添加到选择中,以便为验证提供必要的选项。但是,您还需要删除bankLoginForm.bankLogin.$dirty的检查,因为在用户修改下拉菜单之前,它不会被污染。要使href在下拉菜单无效时消失,您可以在其上添加相反的检查。

<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 =预览

您可以在链接上使用ng-click,并在控制器中处理验证。

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

在视图中:

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

这是更新后的代码http://plnkr.co/edit/CLwFsNIUgt7PPRA3f4HA?p=preview