Angular를 사용하여 앵커 태그 활성화/비활성화JS
직접적 접근 방식을 사용하여 앵커 태그를 활성화/비활성화하려면 어떻게 해야 합니까?
예:
- [편집(Edit)]링크를 클릭하는 동안 작성 및 삭제를 비활성화하거나 회색으로 표시해야 합니다.
- [ Create ]링크를 클릭하는 동안 편집 및 삭제를 비활성화하거나 회색으로 표시해야 합니다.
자바스크립트:
angular.module('ngApp', []).controller('ngCtrl',['$scope', function($scope){
$scope.create = function(){
console.log("inside create");
};
$scope.edit = function(){
console.log("inside edit");
};
$scope.delete = function(){
console.log("inside delete");
};
}]).directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
elem.on('click', function(e){
e.preventDefault();
if(attrs.ngClick){
scope.$eval(attrs.ngClick);
}
});
}
}
};
});
업데이트: href를 비활성화하면 링크 함수가 반환될 때 더 잘 작동합니다.아래 코드가 업데이트되었습니다.
aDisabled
ngClick
지시문은 알파벳 순으로 정렬되어 있기 때문입니다.aDisabled
.tagDisabled
디렉티브는 기능하지 않습니다.
"a" 태그를 "비활성화"하려면 다음과 같이 하십시오.
href
clicked (클릭 시 팔로우되지 않음)ngClick
했을 때- 시 " " " " " " 가 되어 변경됨
disabled
표시
ngDisabled(비활성화)「」의 하고 있습니다.a-disabled
디렉티브에서는 의 모든 .director, "togled"로 되어 있습니다.
myApp.directive('aDisabled', function() {
return {
compile: function(tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";
//return a link function
return function (scope, iElement, iAttrs) {
//Toggle "disabled" to class when aDisabled becomes true
scope.$watch(iAttrs["aDisabled"], function(newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function(e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
비활성 태그를 나타내는 css 스타일을 다음에 나타냅니다.
a.disabled {
color: #AAAAAA;
cursor: default;
pointer-events: none;
text-decoration: none;
}
문제는 조금 달랐습니다.는 tags that an 를 정의하는 앵커 태그를 .href
, , , , , , , 을 .ng-disabled
링크를 클릭했을 때 링크가 이동하지 않도록 합니다. the the the the the the 。href
다음과 같이 링크가 비활성화되어 있는 경우:
<a ng-href="{{isDisabled ? '' : '#/foo'}}"
ng-disabled="isDisabled">Foo</a>
「」는,ng-disabled
요소 스타일링에만 사용됩니다.
비공식 속성을 사용하지 않으려면 직접 스타일링해야 합니다.
<style>
a.disabled {
color: #888;
}
</style>
<a ng-href="{{isDisabled ? '' : '#/foo'}}"
ng-class="{disabled: isDisabled}">Foo</a>
복잡한 답을 원하지 않는 사람들을 위해 Ng-If를 사용하여 유사한 문제를 해결했습니다.
<div style="text-align: center;">
<a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
<span ng-if="ctrl.something == null">I'm just text</span>
</div>
동적 비활성화와 함께 작동하도록 @Nitin의 응답 수정:
angular.module('myApp').directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
elem.on('click', function(e) {
if (attrs.disabled) {
e.preventDefault(); // prevent link click
}
});
}
};
});
이를 통해 비활성화된 Atribute의 존재와 해당 값이 클릭할 때마다 확인됩니다.
면책사항:
OP는 또 다른 답변에 대해 다음과 같은 의견을 제시했습니다.
버튼이나 입력 태그에 ngDisabled를 설정할 수 있습니다.CSS를 사용하면 앵커 태그처럼 보일 수 있지만 별로 도움이 되지 않습니다.지시적인 접근이나 각진 방법을 사용하여 어떻게 할 수 있는지 보는 데 더 열심이었다.
내의 하려면 을 합니다.ng-click
하고, 「」를 설정합니다.ng-disabled
변수 값에 따라 필요할 때 버튼을 비활성화합니다.
아이디어를 주기 위해 Plucker를 업데이트했습니다.
하지만 기본적으로 다음과 같습니다.
<div>
<button ng-click="create()" ng-disabled="state === 'edit'">CREATE</button><br/>
<button ng-click="edit()" ng-disabled="state === 'create'">EDIT</button><br/>
<button href="" ng-click="delete()" ng-disabled="state === 'create' || state === 'edit'">DELETE</button>
</div>
이런 표현에 게으른 평가를 써본 적 있나요?disabled || someAction()
?
컨트롤러에 다음과 같은 정의가 있다고 가정합니다.
$scope.disabled = true;
다음으로 링크를 디세블로 하여 다음과 같은 인라인스타일을 적용할 수 있습니다.
<a data-ng-click="disabled || (GoTo('#/employer/'))" data-ng-style="disabled && { 'background-color': 'rgba(99, 99, 99, 0.5)', }">Higher Level</a>
또는 링크를 해제하고 다음과 같은 클래스를 적용하는 것이 좋습니다.
<a data-ng-click="disabled || (GoTo('#/employer/'))" data-ng-class="{ disabled: disabled }">Higher Level</a>
주의: 다음과 같은 기능이 있습니다.class="disabled"
DOM 요소에 적용됩니다.
이 단계에서는 자신이 하는 일을 처리하기만 하면 됩니다.GoTo()
할 거다.이 경우 관련 상태로 리다이렉트하는 것만큼이나 간단합니다.
$scope.GoTo = function (state) {
if (state != undefined && state.length > 0) {
$window.location.hash = state;
}
};
제한되는 것보다ngDisabled
당신은 당신이 무엇을 하기로 결정하느냐에 따라 제한된다.
이 기술을 사용하여 모듈의 특정 부분에 대한 사용자 접근을 활성화 또는 비활성화하는 권한 수준 검사를 성공적으로 적용했습니다.
다음과 같이 ng-disabled와 유사한 커스텀 디렉티브를 작성하여 특정 요소 세트를 디세블로 할 수 있습니다.
- 커스텀 디렉티브의 속성 변경을 감시합니다(예:
my-disabled
. - 이벤트 핸들러를 추가하지 않고 현재 요소를 복제합니다.
- css 속성을 복제 요소 및 요소의 디세이블 상태를 제공하는 기타 속성 또는 이벤트 핸들러에 추가합니다.
- 감시 대상 속성에서 변경이 검출되면 현재 요소를 복제된 요소로 바꿉니다.
HTML
<a my-disabled="disableCreate" href="#" ng-click="disableEdit = true">CREATE</a><br/>
<a my-disabled="disableEdit" href="#" ng-click="disableCreate = true">EDIT</a><br/>
<a my-disabled="disableCreate || disableEdit" href="#">DELETE</a><br/>
<a href="#" ng-click="disableEdit = false; disableCreate = false;">RESET</a>
자바스크립트
directive('myDisabled', function() {
return {
link: function(scope, elem, attr) {
var color = elem.css('color'),
textDecoration = elem.css('text-decoration'),
cursor = elem.css('cursor'),
// double negation for non-boolean attributes e.g. undefined
currentValue = !!scope.$eval(attr.myDisabled),
current = elem[0],
next = elem[0].cloneNode(true);
var nextElem = angular.element(next);
nextElem.on('click', function(e) {
e.preventDefault();
e.stopPropagation();
});
nextElem.css('color', 'gray');
nextElem.css('text-decoration', 'line-through');
nextElem.css('cursor', 'not-allowed');
nextElem.attr('tabindex', -1);
scope.$watch(attr.myDisabled, function(value) {
// double negation for non-boolean attributes e.g. undefined
value = !!value;
if(currentValue != value) {
currentValue = value;
current.parentNode.replaceChild(next, current);
var temp = current;
current = next;
next = temp;
}
})
}
}
});
해당 스코프에서 토글 기능을 만들어 링크를 회색으로 표시합니다.
먼저 .css 파일에 다음 CSS 클래스를 만듭니다.
.disabled {
pointer-events: none;
cursor: default;
}
.enabled {
pointer-events: visible;
cursor: auto;
}
$scope.state 변수와 $scope.toggle 변수를 추가합니다.다음과 같이 JS 파일에서 컨트롤러를 편집합니다.
$scope.state='on';
$scope.toggle='enabled';
$scope.changeState = function () {
$scope.state = $scope.state === 'on' ? 'off' : 'on';
$scope.toggleEdit();
};
$scope.toggleEdit = function () {
if ($scope.state === 'on')
$scope.toggle = 'enabled';
else
$scope.toggle = 'disabled';
};
HTML에서 태그는 다음과 같이 편집됩니다.
<a href="#" ng-click="create()" class="{{toggle}}">CREATE</a><br/>
<a href="#" ng-click="edit()" class="{{toggle}}">EDIT</a><br/>
<a href="#" ng-click="delete()" class="{{toggle}}">DELETE</a>
링크 자체를 디세블로 하는 문제를 회피하려면 , 기능의 마지막에 DOM CSS 클래스를 변경합니다.
document.getElementById("create").className = "enabled";
다음을 다시 정의할 수 있습니다.a
각도 지시어를 사용한 태그:
angular.module('myApp').directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if ('disabled' in attrs) {
elem.on('click', function(e) {
e.preventDefault(); // prevent link click
});
}
}
};
});
html:
<a href="nextPage" disabled>Next</a>
앵커 태그가 URL이 있는 정적 페이지로 이어질 것으로 예상합니다.버튼은 사용 예에 더 적합하다고 생각합니다.그 후 ngDisabled를 사용하여 비활성화 시킬 수 있습니다.자료 : https://docs.angularjs.org/api/ng/directive/ngDisabled
ui-router v1.0.18
에 대한 지원을 도입했습니다.ng-disabled
닻을 달고
예:<a ui-sref="go" ng-disabled="true">nogo</a>
언급URL : https://stackoverflow.com/questions/23425254/enable-disable-anchor-tags-using-angularjs
'programing' 카테고리의 다른 글
Python이 woocommerce rest api와 연결할 수 없습니다. (0) | 2023.03.21 |
---|---|
Maven 및 Spring Boot - 해결할 수 없는 부모 POM - repo.spring.io (알 수 없는 호스트) (0) | 2023.03.21 |
reactjs를 사용하여 Facebook API 로그인 구현 (0) | 2023.03.21 |
oracle에서 열 varchar를 clob으로 변경하는 방법 (0) | 2023.03.21 |
Spring 4.x/3.x (Web MVC) REST API와 JSON2 POST 요청, 어떻게 하면 제대로 할 수 있을까요? (0) | 2023.03.21 |