요소 포커스를 각도 방향으로 설정
각도가 있는 포커스 요소의 설정 예를 찾아본 결과, 대부분은 어떤 변수를 사용하여 감시하고 포커스를 설정하고 싶은 필드마다 1개의 다른 변수를 사용하고 있는 것을 알 수 있었습니다.여러 개의 필드가 있는 형태에서는 다양한 변수가 내포되어 있습니다.
저는 jquery를 염두에 두고, 그러나 각도로 그것을 하고 싶다고 생각하고, 원소의 ID를 사용해 어떤 함수에 초점을 맞추는 솔루션을 만들었습니다.그래서 각도로는 매우 새로운 것이기 때문에, 만약 그렇게 하는 것이 맞다면, 문제가 있거나, 어떤 것이든, 각도로 이것을 더 잘 할 수 있는 것이 있으면, 의견을 듣고 싶습니다.
기본적으로 디렉티브 또는 디폴트의 focusElement를 사용하여 사용자가 정의한 스코프 값을 감시하는 디렉티브를 작성합니다.이 값이 요소의 ID와 같으면 해당 요소 집합 포커스 자체가 됩니다.
angular.module('appnamehere')
.directive('myFocus', function () {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
if (attrs.myFocus == "") {
attrs.myFocus = "focusElement";
}
scope.$watch(attrs.myFocus, function(value) {
if(value == attrs.id) {
element[0].focus();
}
});
element.on("blur", function() {
scope[attrs.myFocus] = "";
scope.$apply();
})
}
};
});
어떤 이유로든 초점을 맞춰야 하는 입력은 이렇게 한다.
<input my-focus id="input1" type="text" />
포커스를 설정할 요소:
<a href="" ng-click="clickButton()" >Set focus</a>
포커스를 설정하는 기능의 예는 다음과 같습니다.
$scope.clickButton = function() {
$scope.focusElement = "input1";
}
각도가 있는 좋은 해결책인가요?제 경험상 아직 모르는 문제가 있나요?
솔루션의 문제는 새로운 범위를 만드는 다른 지침에 얽매이면 제대로 작동하지 않는다는 것입니다.ng-repeat
더 나은 해결책은 컨트롤러 내에서 요소에 초점을 맞추거나 html에서 선언적으로 요소에 초점을 맞출 수 있는 서비스 함수를 만드는 것입니다.
자바스크립트
서비스
.factory('focus', function($timeout, $window) {
return function(id) {
// timeout makes sure that it is invoked after any other event has been triggered.
// e.g. click events that need to run before the focus or
// inputs elements that are in a disabled state but are enabled when those events
// are triggered.
$timeout(function() {
var element = $window.document.getElementById(id);
if(element)
element.focus();
});
};
});
지시.
.directive('eventFocus', function(focus) {
return function(scope, elem, attr) {
elem.on(attr.eventFocus, function() {
focus(attr.eventFocusId);
});
// Removes bound events in the element itself
// when the scope is destroyed
scope.$on('$destroy', function() {
elem.off(attr.eventFocus);
});
};
});
컨트롤러
.controller('Ctrl', function($scope, focus) {
$scope.doSomething = function() {
// do something awesome
focus('email');
};
});
HTML
<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>
이 솔루션에 대해서는 디렉티브를 생성하여 특정 조건이 충족되었을 때 포커스를 획득해야 하는 DOM 요소에 부가하기만 하면 됩니다.이 접근방식을 따름으로써 컨트롤러를 DOM 요소 ID에 결합하는 것을 피할 수 있습니다.
샘플 코드 지시어:
gbndirectives.directive('focusOnCondition', ['$timeout',
function ($timeout) {
var checkDirectivePrerequisites = function (attrs) {
if (!attrs.focusOnCondition && attrs.focusOnCondition != "") {
throw "FocusOnCondition missing attribute to evaluate";
}
}
return {
restrict: "A",
link: function (scope, element, attrs, ctrls) {
checkDirectivePrerequisites(attrs);
scope.$watch(attrs.focusOnCondition, function (currentValue, lastValue) {
if(currentValue == true) {
$timeout(function () {
element.focus();
});
}
});
}
};
}
]);
사용 가능한 용도
.controller('Ctrl', function($scope) {
$scope.myCondition = false;
// you can just add this to a radiobutton click value
// or just watch for a value to change...
$scope.doSomething = function(newMyConditionValue) {
// do something awesome
$scope.myCondition = newMyConditionValue;
};
});
HTML
<input focus-on-condition="myCondition">
가능한 한 DOM 룩업, 워치, 글로벌 이미터를 피하고 싶기 때문에, 보다 직접적인 어프로치를 사용하고 있습니다.디렉티브 요소에 초점을 맞춘 단순 함수를 할당하려면 디렉티브를 사용합니다.그런 다음 컨트롤러 범위 내에서 필요한 경우 해당 기능을 호출합니다.
스코프에 접속하기 위한 간단한 어프로치를 다음에 나타냅니다.controller-as 구문의 취급에 대해서는, 완전한 스니펫을 참조해 주세요.
지시:
app.directive('inputFocusFunction', function () {
'use strict';
return {
restrict: 'A',
link: function (scope, element, attr) {
scope[attr.inputFocusFunction] = function () {
element[0].focus();
};
}
};
});
및 html:
<input input-focus-function="focusOnSaveInput" ng-model="saveName">
<button ng-click="focusOnSaveInput()">Focus</button>
또는 컨트롤러:
$scope.focusOnSaveInput();
angular.module('app', [])
.directive('inputFocusFunction', function() {
'use strict';
return {
restrict: 'A',
link: function(scope, element, attr) {
// Parse the attribute to accomodate assignment to an object
var parseObj = attr.inputFocusFunction.split('.');
var attachTo = scope;
for (var i = 0; i < parseObj.length - 1; i++) {
attachTo = attachTo[parseObj[i]];
}
// assign it to a function that focuses on the decorated element
attachTo[parseObj[parseObj.length - 1]] = function() {
element[0].focus();
};
}
};
})
.controller('main', function() {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<body ng-app="app" ng-controller="main as vm">
<input input-focus-function="vm.focusOnSaveInput" ng-model="saveName">
<button ng-click="vm.focusOnSaveInput()">Focus</button>
</body>
이 접근법의 이유에 대한 자세한 설명과 컨트롤러 사용 시 코드 스니펫을 확장하기 위해 편집되었습니다.
시도해 보세요
angular.element('#<elementId>').focus();
예를 들어,
angular.element('#txtUserId').focus();
나한테는 효과가 있어요.
또 다른 옵션은 Angular의 내장된 pub-sub 아키텍처를 사용하여 초점을 맞추도록 지시하는 것입니다.다른 접근 방식과 비슷하지만 속성에 직접 연결되지 않고 대신 특정 키의 범위를 엿봅니다.
지시:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
컨트롤러:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
나는 표현을 쓰는 것을 선호했다.이렇게 하면 필드가 유효할 때 버튼에 포커스를 맞추고 일정 길이에 도달하며 로드 후에 포커스를 맞출 수 있습니다.
<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">
복잡한 형태에서는 초점을 맞추기 위해 추가 범위 변수를 작성할 필요도 줄어듭니다.
https://stackoverflow.com/a/29963695/937997 를 참조해 주세요.
언급URL : https://stackoverflow.com/questions/25596399/set-element-focus-in-angular-way
'it-source' 카테고리의 다른 글
jQuery 검증자 및 AJAX를 사용하는 사용자 지정 규칙 (0) | 2023.02.12 |
---|---|
노드의 부정한 JSON.parse()를 안전하게 처리한다. (0) | 2023.02.12 |
반응 구성 요소에 iframe 삽입 (0) | 2023.02.12 |
는 Tinymce로 감겨져 .는 Tinymce로 감겨져 .는 Tinymce로 감겨져 .태그. CSS가 돌아다니거나 텍스트 에디터를 해킹하거나 (0) | 2023.02.12 |
AJAX 어플리케이션의 뒤로 버튼 호출 대행 수신 (0) | 2023.02.12 |