前言

Angularjs的思维方式是通过数据带动DOM变动,通常依托指令与控制器的配合来实现。就表单操作上,提供了几乎完备的操作体验。对于官方没有实现的功能,只能自己来实现。比如说在做表单校验时,使用编码方式实现控件的focus

简易表单

如下为一个简易表单,auto-focus-when为负责控件focus的指令。

html

<form class="form-horizontal" name="form" role="form" ng-controller="FocusCtrl"> <div class="form-group"> <label for="username" class="col-sm-2 control-label" >用户名</label> <div class="col-sm-5"> <input type="text" ng-model="username" name="username" id="username" class="form-control" auto-focus-when="usernameFocus" > </div> </div> <div class="form-group"> <label for="bookname" class="col-sm-2 control-label" >书名</label> <div class="col-sm-5"> <input type="text" ng-model="bookname" name="bookname" id="bookname" class="form-control" auto-focus-when="booknameFocus"> </div> </div> </form>

自定义指令

指令内容比较简单,不做过多说明。

javascriptangular.module('shuffleApp', [])
  .directive('autoFocusWhen', ['$log','$timeout', function($log, $timeout) {
      return {
          restrict: 'A',
          scope: {
              autoFocusWhen: '='
          },
          link: function(scope, element) {
              scope.$watch('autoFocusWhen', function(newValue) {
                  if (newValue) {
                     $timeout(function(){
                         element[0].focus();
                     })
                  }
              });

              element.on('blur', function() {
                  scope.$apply(function() {
                      scope.autoFocusWhen = false;
                  })
              })
          }
      }

控制器测试

此处控制器与指令本是同级,此处分开说明之用。通过控制器内部的变量控制,即可实现表单控件的focus控制。

javascriptangular.module('shuffleApp', [])
  .controller('FocusCtrl', ['$scope', '$interval', function($scope, $interval) {
      $scope.usernameFocus = false;
      $scope.booknameFocus = true;
      $interval(function() {
          $scope.usernameFocus = $scope.usernameFocus ? false : true;
          $scope.booknameFocus = $scope.booknameFocus ? false : true;
      }, 1500, 3);
  }])

联系方式

QQ:491229492

Email: hjj491229492@hotmail.com


怀疑真爱的流浪者jason
923 声望62 粉丝

For every single second in life, I want to fight with the monster deep within my heart , and I want to win.........


引用和评论

0 条评论