sourcecode

입력 자동 포커스 속성

copyscript 2023. 3. 5. 10:17
반응형

입력 자동 포커스 속성

내 코드에 다음과 같은 위치가 있습니다.

<input data-ng-disabled="SOME_SCOPE_VARIABLE" />

저도 이렇게 사용할 수 있으면 좋겠습니다.

<input data-ng-autofocus="SOME_SCOPE_VARIABLE" />

또는 ng-style 방식을 모방하는 것이 좋습니다.

<input data-ng-attribute="{autofocus: SOME_SCOPE_VARIABLE}" />

이것이 현재 버전의 AngularJS에 있습니까?코드에 BOUAL_ATTR이 있다는 것을 알아챘습니다. 모든 속성을 Angular로 가져옵니다.JS는 지원합니다.버전 변경이나 업데이트를 잊어버릴까 봐 수정하고 싶지 않습니다.

업데이트: AngularJS는 이제 포커스에 초점을 맞춘 표현을 평가하는 지침을 가지고 있지만, 저는 여기서 완전성을 위해 언급합니다.


Angular의 현재 버전JS에는 포커스 지시가 없지만 로드맵에 나와 있습니다.공교롭게도, 어제 메일링 리스트에서 이것에 대해 이야기하고 있었습니다만, 저는 이것을 생각해 냈습니다.

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );

                }
            });
        }
    };
});

이는 사용자가 요청한 대로 범위 변수를 수행합니다.

<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

여기 바이올린이 있습니다.http://jsfiddle.net/ANfJZ/39/

이것은 내장된 ngAtr 속성 바인딩을 사용하여 수행할 수 있습니다.

<input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">

autofocus 속성은 다음과 같이 추가됩니다.SOME_SCOPE_VARIABLE정의되어 있다(비록false) 。이 경우 삭제됩니다.undefined그래서 나는 거짓된 가치를 강요한다.undefined.

$scope.SOME_SCOPE_VARIABLE = someVar || undefined;

이 디렉티브는 다음과 같은 기능을 합니다.

angular.module('utils.autofocus', [])
.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    scope: {'autofocus':'='}
    link : function($scope, $element) {
      $scope.$watch 'autofocus', function(focus){
        if(focus){
          $timeout(function() {
            $element[0].focus();
          });
        }
      }
    }
  }
}]);

여기서부터 : https://gist.github.com/mlynch/dd407b93ed288d499778

scope.doFocus = function () {
                $timeout(function () {
                        document.getElementById('you_input_id').focus();
                    });
            };

다음과 같은 지시문 생성

.directive('autoFocus', ['$timeout', function ($timeout) {
        return {
            restrict: 'A',
            link: function ($scope, $element) {
                $timeout(function () {
                    $element[0].focus();
                });
            }
        }



<input type="text" auto-focus class="form-control msd-elastic" placeholder="">

입력에 대해 일반적인 자동 포커스를 사용합니다.<input autofocus>

그런 다음 각도가 준비되면 자동 포커스를 사용하여 첫 번째 가시 입력에 포커스를 설정합니다.

angular.element(document).ready(function() {
  $('input[autofocus]:visible:first').focus();
});

이게 도움이 됐으면 좋겠다.

다음과 같은 두 가지 커스텀 디렉티브를 사용하여 작업을 수행했습니다.

(function(angular) {
  'use strict';

  /* @ngInject */
  function myAutoFocus($timeout) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        $timeout(function() {
          element[0].focus();
        }, 300);
      }
    };
  }

  function myFocusable() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var focusMethodName = attrs.myFocusable;
        scope[focusMethodName] = function() {
          element[0].focus();
        };
      }
    };
  }

  angular
    .module('myFocusUtils', [])
    .directive('myAutoFocus', myAutoFocus)
    .directive('myFocusable', myFocusable);

}(angular));

Atribute를 추가한 경우my-auto-focus300ms 후에 포커스를 받습니다.포커스를 설정하기 전에 다른 비동기 컴포넌트가 로드되도록 하려면 값을 0이 아닌 300으로 설정합니다.

아트리뷰트my-focusable현재 스코프에 함수를 만듭니다.이 함수는 호출 시 요소에 포커스를 설정합니다.범위 내에 무엇인가가 생성되므로 덮어쓰지 않도록 주의하십시오.

이렇게 하면 Angular의 다이제스트 사이클에 무언가를 추가할 필요가 없습니다(watch뷰에서 모두 실행할 수 있습니다.

<input my-focusable="focusOnInput"></input>        
<button ng-click="focusOnInput()">Click to focus</button>

JSFiddle을 만들어서myFocusable디렉티브 : http://jsfiddle.net/8shLj3jc/

무슨 이유인지는 모르겠지만myAutoFocus디렉티브는 JSFiddle에서는 동작하지 않지만 my page에서는 동작합니다.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl"> 
  <div ng-repeat="x in names">
     <input ng-attr-focus={{$first}} value="{{x.name + ', ' + x.country }}" />
  </div>
</div>

<script>

        var myApp = angular.module('myApp', []);
        myApp.controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'x1',country:'y1'},
        {name:'x2',country:'y2'},
        {name:'x3',country:'y3'}
    ];
});

        myApp.directive("focus", function(){
            return {
                restrict: "A",
                link: function link(scope, element, attrs) {

                      if(JSON.parse(attrs.focus)){
                          element[0].focus();
                      }
                }
            };
        });
</script>
</body>
</html>

위의 커스텀 디렉티브를 작성했습니다.

  • 는 항상 첫 번째 입력 요소에 초점을 맞춥니다.
  • 는 Ajax 데이터, 브라우저의 뒤로/앞으로 버튼에 대해 작동합니다.
  • Chrome 및 Firefox에서 테스트됨(기본 자동 포커스는 여기서 지원되지 않음)

JSON.parse html boolean true는 "true"입니다.
if의 경우 입니다.===에 초점을 맞춥니다.

따라서 $120이 없어도 자동 포커스를 이렇게 사용할 수 있습니다.

    <input type="text" ng-show="{{condition}}" class='input-class'></input>
    angular.element(document).ready(function(){
    angular.element('.input-class')[0].focus();
    });

위에서 언급한 다른 항목들을 조합하면:

JS 코드:

myApp.directive('ngAutofocus', ['$timeout', function ($timeout) {
    var linker = function ($scope, element, attrs) {
        $scope.$watch('pageLoaded', function (pageLoaded) {
            if (pageLoaded) {
                $timeout(function () {
                    element[0].focus();
                });
            }
        });
    };

    return {
        restrict: 'A',
        link: linker
    };
}]);

HTML:

  <input type="text" ng-model="myField" class="input-block-level edit-item" ng-autofocus>

페이지의 초기 로드 방식에서 pageLoaded를 true로 설정합니다.

    var loadData = function () {
        ..
        return $http.get(url).then(function (requestResponse) {
           $scope.pageLoaded = true;
......
}

언급URL : https://stackoverflow.com/questions/14859266/input-autofocus-attribute

반응형