AngularJS:如果是原始的,则点击,如果是脏的,则有效

时间:2017-07-11 19:48:04

标签: javascript angularjs forms

我有一个输入字段:

<input name="fName" type="text" class="form-control dude.firstName"
     ng-trim="false"
     ng-pattern="patterns.name"
     ng-model="dude.firstName"
     ng-model-options="{ updateOn: 'blur' }"
     required>
<span class="error" ng-show="idForm.fName.$error.pattern">
     Please only use letters, forward slashes, and hyphens
</span>

我的要求是:

  1. 如果用户没有更改任何内容,则需要运行saveIdentification
  2. 如果用户更改了某些内容但无效,请停止并允许该表单显示消息
  3. 如果用户更改了某些内容并且该内容有效,请运行saveIdentification

    <span 
        ng-show="localEditing.id=='SAVE'" 
        tabindex="0" 
        title="Save Changes" 
        class="globalIcon-save action-edit-button" 
        ng-click="(idForm.$pristine || (idForm.$dirty && idForm.$valid)) && saveIdentification()">
    </span>
    
  4. 上述解决方案满足要求1和2但不满足要求3.如果表单已更改且有效,则不会保存。

2 个答案:

答案 0 :(得分:1)

请参阅下面的代码段。我只是对您的代码稍作修改,以便在saveIdentification函数中接收表单对象作为参数。

注意我添加了ng-maxlength="3"的输入,以便重现表单无效的场景(当输入文本大于3时)

当您描述的条件满足时,浏览器控制台(devtools)中会记录“ ran saveIdentification!”文本。

angular
  .module('app', [])
  .controller('myCtrl', function() {

    var vm = this;

    vm.wizard = {
      saveIdentification: fnSaveIdentification
    };

    return vm.wizard;

    function fnSaveIdentification(form) {debugger;
      if (form && (form.$pristine || form.$valid)) {    //<-- Condition here!
        console.log('ran saveIdentification!');
      }
    }

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl as ctrl">

  <form name="myForm">
    <input name="i1" type="text" ng-maxlength="3" ng-model="ctrl.input">
    <a href="#" ng-click="ctrl.saveIdentification(myForm)">Submit</a>

    <!-- Display message here!! (modify as you need it)-->
    <span ng-show="myForm.$invalid">Form is invalid</span>
  </form>

</div>

答案 1 :(得分:0)

试试这个:

ng-disabled="(idForm.$dirty && idForm.$invalid))"
ng-click="saveIdentification()"
>

<span ng-show="(idForm.$dirty && idForm.$invalid))">
Your error message goes here!!!
</span>