单击(ng-show - 表单验证)后再次隐藏提交按钮

时间:2016-01-27 15:28:38

标签: angularjs

我有以下代码,如果两个输入都有值且inputURL是有效的URL,则显示a.btn锚点。工作正常但我想在点击时再次隐藏按钮,我该怎么做,我是否重置表单或实际隐藏点击按钮?

  <form name="myForm" class="row inputs">
      <div class="col-xs-5">
          <label for="exampleInputPassword1">Enter a Title/Description</label>
            <input name="inputName" type="text" id="urlName" class="form-control" placeholder=""  ng-model="mvName" required>
        </div>
        <div class="col-xs-5">
            <label for="exampleInputPassword1">Enter a URL</label>
            <input type="url" name="inputURL" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" required>
      </div>
      <div class="col-xs-2">
          <a href="javascript:" ng-click="saveToList($event)" class="btn btn-block post" ng-show="myForm.$valid">Post</a>
      </div>

    </form>

3 个答案:

答案 0 :(得分:1)

我以前做过的是在控制器中创建一个范围变量:

$scope.formSubmitted = false;

然后在saveToList函数中将$ scope.formSubmitted设置为true。从这里你有几个选择。如果您是“发布”按钮是一个实际按钮,那么您可以设置禁用属性。您还可以在saveToList函数中检查formSubmitted是否为true,如果为true,则不继续。或者您可以将ng-show更改为:

ng-show="myForm.$valid && !formSubmitted"

答案 1 :(得分:0)

你可以这样做:

定义另一个$scope.someToggle变量,并为其分配true,然后在该按钮的ng-show添加ng-show="myForm.$valid && someToggle"。然后在saveToList($event)函数的结尾(或回调)中,将$scope.someToggle设置为false

你也可以把它放在两个输入上:ng-change = "someToggle = true"所以每当它们改变时(点击保存按钮后)你就能把它带回来......

答案 2 :(得分:0)

<强> HTML

    <body ng-app="myApp">
<div ng-controller="formCtrl">
<form name="myForm" class row inputs">
      <div class="col-xs-5">
          <label for="exampleInputPassword1">Enter a Title/Description</label>
            <input name="inputName" type="text" id="urlName" class="form-control" placeholder=""  ng-model="mvName" required>
        </div>
        <div class="col-xs-5">
            <label for="exampleInputPassword1">Enter a URL</label>
            <input type="url" name="inputURL" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" required>
      </div>
      <div class="col-xs-2">
          <a href="javascript:" ng-click="saveToList($event)" class="btn btn-block post" ng-show="myForm.$valid">Post</a>
      </div>

    </form>
    </div>
</body>

<强>控制器

var app = angular.module('myApp', []);

app.controller('formCtrl', function($scope) {   

    $scope.saveToList = function() {            
        $scope.mvName = '';
        $scope.mvUrl = '';              
    }

});

<强> 替代

使用范围变量而不使表单无效

 <a href="javascript:" ng-click="saveToList($event)" class="btn btn-block post" ng-show="myForm.$valid {{logicalExp}} !formSubmitted">Post</a>

app.controller('formCtrl', function($scope) {   

    $scope.logicalExp = "||";
    $scope.formSubmitted = true;

    $scope.saveToList = function() {            
        $scope.logicalExp = "&&";
          $scope.formSubmitted = true;              
    }
  });

问题是,用户需要通过删除输入的值自行使表单无效,然后隐藏超链接。