如何在angularjs 1.3中将表单中的特定字段设置为脏

时间:2014-10-06 18:07:47

标签: javascript angularjs

我想将一个特定表单的字段设置为脏,因为我手动更改了该值。我已经离开了SO线程Angular.js programmatically setting a form field to dirty,但没有运气。

以下是我的问题的示例副本。     Plunk

<html ng-app="sampleApp">

<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0- rc.4/angular.min.js"></script>
 <style type="text/css">
 input.ng-invalid {
  border: 1px solid red;
 }
input.ng-valid {
  border: 1px solid green;
}
input.ng-pristine {
  border-color: #FFFF00;
}
</style>
<script type="text/javascript">
 var sampleApp = angular.module("sampleApp", []);
 sampleApp.controller('sampleCtrl', ['$scope', '$http', '$timeout',
   function($scope, $http, $timeout) {
     $scope.userData = {
       username: "",
     };

     $timeout(function() {
       $scope.userData.username = '$#deepak';
     }, 5000);

   }
 ]);
 sampleApp.directive('myUsername', [
   function() {
     // Runs during compile
     return {

       require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent 
       link: function($scope, iElm, iAttrs, controller) {

         controller.$parsers.unshift(function(value) {
           //allow only alphanumeric characters
           var reg = /^\w+$/;
           var isValidUsername = reg.test(value);
           controller.$setValidity('username', isValidUsername);

           return isValidUsername ? value : undefined;
         });

         controller.$formatters.unshift(function(value) {
           var reg = /^\w+$/;
           var isValidUsername = reg.test(value);

           controller.$setValidity('username', isValidUsername);
          $scop  e.registrationForm.username.$setViewValue($scope.registrationForm.username.$viewValue);
           return value;
         })

       }
     };
   }
 ]);
  </script>
  </head>

 <body ng-controller="sampleCtrl">
  <div ng-show="bShowStatus">
   {{message}}
   <ul ng-repeat="err in errors">
     {{err}}
   </ul>
  </div>
  <form name="registrationForm" ng-submit="submitForm()" novalidate>
    UserName
    <br>
    <input type="text" name="username" ng-model="userData.username" ng-model-options="{updateOn:  'blur'}" my-username>&nbsp;&nbsp;
    <span ng-show="registrationForm.username.$dirty && registrationForm.username.$error.username">
            Invalid Username.
        </span>

 <br>
 <br>
 <input type="submit" value="Submit">
 </form>
</body>

</html>

在示例中,我在5秒后修改用户名(仅用于示例)。同时,我想将字段设置为脏并启动验证并显示错误消息。

请帮忙。

2 个答案:

答案 0 :(得分:1)

Deepak

这是带有解决方案http://plnkr.co/edit/69Beli?p=preview的plnkr。不是直接更新$ scope.userData.username并绕过'model to view'的解析器管道,而是使用jQuery更新输入字段并触发'change'事件并使用Angular提供的'view to model'管道。

            $timeout(function(){
              jQuery("[name=username]").val('$#deepak');
              jQuery("[name=username]").trigger('change');
            }, 5000);

另一个带有$ render的plnkr http://plnkr.co/edit/Zct92r已实现。这是'模型查看'管道,$ render在$ parser之后调用,并根据错误设置样式。

    controller.$render = function() {
      console.log('in render');
      iAttrs.$set('value', controller.$viewValue);
      if (controller.$invalid && controller.$viewValue.length !== 0) {
        iElm.css("border", "1px solid red");
      } else if (controller.$viewValue.length === 0) {
        iElm.css("border", "1px solid gold");
      } else {
        iElm.css("border", "1px solid green");
      }
    };

这两种解决方案都像黑客一样,而且渲染效果更好。无论在$ render中设置什么,都必须在$ parser中进行补偿并撤消。

答案 1 :(得分:0)

嗯,它适用于我使用线程(Angular.js programmatically setting a form field to dirty)中讨论的$ dirty标志:

$timeout(function(){
    $scope.userData.username = '$#deepak';
    $scope.registrationForm.username.$dirty = true;
}, 5000);

在这里看到工作的plunker: http://plnkr.co/edit/ZvX62jJsklPLyw7Q4nlT?p=preview