AngularJs专注于特定领域

时间:2016-02-25 05:39:18

标签: javascript angularjs

这里我使用angularJs创建了简单程序,这里如何在发生错误时关注特定字段 提前致谢

 var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  
  
  $scope.save=function(){
    
      if($scope.firstName != undefined){
          if($scope.firstName.length < 3)   {
              alert("Please Enter More that 3 char");
            
            }
        
        
        }
    
    }
	
	
     
})
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp"  ng-controller="myCtrl">
  
  <form>
      <input type="text" ng-model="firstName"/>
      <input type="submit"  ng-click="save()"/>
  </form>
  
  
</body>


   

2 个答案:

答案 0 :(得分:1)

尝试这个,当您尝试提交表单时,它将聚焦包含错误的元素 你的HTML:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp"  ng-controller="myCtrl">

  <form name="formname" id="form1" novalidate ng-submit="form(formname)">
      <input type="text" ng-model="firstName"/>
      <input type="submit"/>
  </form>


</body>

并在您的控制器中编写此代码

$scope.form =  function (form) {
                var firstError = null;
                if (form.$invalid) {

                    var field = null, firstError = null;
                    for (field in form) {
                        if (field[0] != '$') {
                            if (firstError === null && !form[field].$valid) {
                                firstError = form[field].$name;
                            }

                            if (form[field].$pristine) {
                                form[field].$dirty = true;
                            }
                        }
                    }
                    angular.element('.ng-invalid[name=' + firstError + ']').focus();
                   return;
                } else {

                    $scope.save()
                }
            }

答案 1 :(得分:0)

以下是关注元素的简单且最简单的方法。你将能够使用javascript专注于元素。

<body ng-app="myApp" ng-controller="myCtrl">
    <form>
        <input type="text" ng-model="firstName" id="firstName" />
        <input type="submit" ng-click="save()" />
    </form>
</body>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, $window) {
    $scope.save = function () {
        if ($scope.firstName != undefined) {
            if ($scope.firstName.length < 3) {
                alert("Please Enter More that 3 char");
                var element = $window.document.getElementById("firstName");
                if (element)
                    element.focus();
            }
        }
      }
    });
</script>