AngularJS - Attribute Directive 조건부로 사용
이미지 끌기를 지원하기 위해 "끌기 가능" 지시문을 사용하고 있습니다.단, 사용자의 역할에 따라 특정 사용자 그룹에 대해 이미지 끌기를 비활성화해야 합니다.저는 다음 코드를 사용했습니다.
<!--draggable attribute is used as handle to make it draggable using jquery event-->
<li ng-repeat="template in templates" draggable id="{{template._id}}" type="template" class="template-box">
<!-- Images and other fields are child of "li" tag which can be dragged.-->
</li>
방법dragSupported
템플릿 범위 내에 있으며 반환됩니다.true
또는false
두 개의 큰 복제를 만들고 싶지 않습니다.<li>
요소(사용)ng-if
에 의해 반환되는 각 값에 대해dragSupported()
즉, 이 문제를 해결하기 위해 다음과 같은 접근방식을 찾고 있지 않습니다.
<!--draggable attribute is used as handle to make it draggable using jquery event-->
<li ng-if="dragSupported() ==true" ng-repeat="template in templates" draggable id="{{template._id}}" type="template" class="template-box">
<!-- Images and other fields are child of "li" tag which can be dragged.-->
</li>
<!--remove "draggable" directive as user doesn't have permission to drag file -->
<li ng-if="dragSupported() !=true" ng-repeat="template in templates" id="{{template._id}}" type="template" class="template-box">
<!-- Images and other fields are child of "li" tag which can be dragged.-->
</li>
코드의 중복을 피하기 위한 다른 방법이 있습니까?
ng-attr-<attrName>
HTML 속성을 조건부로 선언하는 지원은 동적 제목으로 Angular에 포함되어 있습니다.ng-attr-<attrName>
지시.
예
이 경우 코드는 다음과 같습니다.
<li
id="{{template._id}}"
class="template-box"
type="template"
ng-repeat="template in templates"
ng-attr-draggable="dragSupported() === true"
></li>
데모
여기에서는 다음 값의 사용 예를 보여 줍니다.true
,false
,undefined
,null
,1
,0
,그리고.""
. 일반적으로 false 값이 예기치 않은 결과를 초래할 수 있습니다.
제안해 주셔서 감사합니다.나는 여기서 조금 다른 접근을 했다."scope" 변수를 변경하지 않기 때문에 "attrs"를 사용하여 드래그 허용 여부를 확인했습니다.다음은 지금까지 좋아 보이는 어프로치 I 툴입니다.
지시 코드:
app.directive('draggable', function () {
return {
// A = attribute, E = Element, C = Class and M = HTML Comment
restrict: 'A',
replace:true,
link: function (scope, element, attrs) {
if(attrs.allowdrag =="true")
{
element.draggable({
cursor: 'move',
helper: 'clone',
class:'drag-file'
});
}
}
}
});
HTML 코드:
<ul>
<!--draggable attribute is used as handle to make it draggable using jquery event-->
<li ng-repeat="template in templates" draggable allowdrag="{{userHasPrivilege()}}" >
<!--Ohter code part of li tag-->
</li>
</ul>
컨트롤러에 userHasPrivilege()가 실장되어 있습니다.
이것이 올바른 방법인지 아닌지 확실하지 않다.생각을 찾고 있다.
요소에 Atribute를 직접 추가하거나 요소에서 Atribute를 제거하는 방법은 없습니다.단, 조건이 충족되면 Atribute를 요소에 추가하는 디렉티브를 작성할 수 있습니다.접근방식을 설명할 수 있는 걸 만들어 놨어요
데모: http://jsfiddle.net/VQfcP/31/
지시.
myApp.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
canDrag: '&'
},
link: function (scope, el, attrs, controller) {
/*
$parent.$index is ugly, and it's due to the fact that the ng-repeat is being evaluated
first, and then the directive is being applied to the result of the current iteration
of the repeater. You may be able to clean this by transcluding the repeat into the
directive, but that may be an inappropriate separation of concerns.
You will need to figure out the best way to handle this, if you want to use this approach.
*/
if (scope.canDrag&& scope.canDrag({idx: scope.$parent.$index})) {
angular.element(el).attr("draggable", "draggable");
}
}
};
});
HTML
<ul>
<!-- same deal with $parent -->
<li ng-repeat="x in [1, 2, 3, 4, 5]" my-directive="true" can-drag="checkPermissions(idx)">{{$parent.x}}</li>
</ul>
컨트롤러
function Ctl($scope) {
$scope.checkPermissions = function(idx) {
// do whatever you need to check permissions
// return true to add the attribute
}
}
앞의 예에서는 효과가 없었기 때문에, 다른 어프로치를 채용했습니다.커스텀 디렉티브를 사용하는 것과 관련이 있는 것은 아닐까요?아마 누군가는 그것을 해결할 수 있을 것이다.
이 예에서는 ui-grid를 사용하지만 모든 ui-grid가 페이지 번호를 사용해야 하는 것은 아닙니다."paggated" 속성을 전달하고 true/false에 따라 지시문을 $compile합니다.꽤 잔인해 보이지만 그것이 사람들을 긍정적인 방향으로 이끌 수 있기를 바란다.
HTML
<sync-grid service="demand" paginated="true"></sync-grid>
지시.
angular
.module('app.directives')
.directive('syncGrid', ['$compile', SyncGrid]);
function SyncGrid($compile){
var nonPaginatedTemplate = '' +
'<div>' +
' <div ui-grid="gridOptions" class="grid"></div>' +
'</div>';
var paginatedTemplate = '' +
'<div>' +
' <div ui-grid="gridOptions" class="grid" ui-grid-pagination></div>' +
'</div>';
return {
link: link,
restrict: 'E',
replace: true
};
function link(scope, element, attrs) {
var isPaginated = attrs['paginated'];
var template = isPaginated ? paginatedTemplate : nonPaginatedTemplate;
var linkFn = $compile(template);
var content = linkFn(scope);
element.append(content);
// Continue with ui-grid initialization code
// ...
}
}
언급URL : https://stackoverflow.com/questions/18798456/angularjs-use-attribute-directive-conditionally
'programing' 카테고리의 다른 글
오류: '.docker-compose.yml' 파일에서 볼륨은 문자열이 아닌 매핑이어야 합니다. (0) | 2023.03.26 |
---|---|
DAG(Directed Acyclic Graph)를 JSON으로 저장하려면 어떻게 해야 합니까? (0) | 2023.03.26 |
MongoDB: 필드가 존재하지 않아 문서를 검색하시겠습니까? (0) | 2023.03.26 |
Oracle 데이터베이스를 사용할 때 Hibernate는 기본적으로 어떤 부울 데이터 유형을 매핑합니까? (0) | 2023.03.26 |
다른 컨트롤러로부터의 디렉티브컨트롤러 호출방식 (0) | 2023.03.26 |