AngularJS - Use attribute directive conditionally

前端 未结 4 1588
走了就别回头了
走了就别回头了 2020-12-23 13:48

I am using \"draggable\" directive to support image dragging. However, as per the role of the user, I need to disable image dragging for certain groups of users. I have used

相关标签:
4条回答
  • 2020-12-23 14:00

    I used a different approach as the previous examples didn't work for me. Perhaps it has to do with using custom directives? Perhaps someone can clear that up.

    In my particular example, I'm using ui-grid, but not all ui-grids should use pagination. I pass in a "paginated" attribute and then $compile the directive based on true/false. Seems pretty brutish but hopefully it can push people in a positive direction.

    HTML

    <sync-grid service="demand" paginated="true"></sync-grid>
    

    Directive

    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
            // ...
    
        }
    }
    
    0 讨论(0)
  • 2020-12-23 14:02

    Thanks Jason for your suggestion. I took little different approach here. Since I don't want to change the "scope" variable therefore I used "attrs" to check if drag is allowed or not. Following is approach I tool which seems good so far.

    Directive code:

    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 Code:

    <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>
    

    Controller is having implementation of userHasPrivilege().

    Not sure if this is correct way or not. Looking for thoughts.

    0 讨论(0)
  • 2020-12-23 14:02

    There is no way to directly add or remove an attribute from an element. However, you could create a directive that simply adds the attribute to the element when the condition is met. I've put something together that illustrates the approach.

    Demo: http://jsfiddle.net/VQfcP/31/

    Directive

    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>
    

    Controller

    function Ctl($scope) {
       $scope.checkPermissions = function(idx) {
         // do whatever you need to check permissions
         // return true to add the attribute
       }
    }
    
    0 讨论(0)
  • 2020-12-23 14:07

    ng-attr-<attrName>

    Support for conditionally declaring an HTML attribute is included with Angular as the dynamically-titled ng-attr-<attrName> directive.

    Official Docs for ng-attr

    Example

    In your case, the code might look like this:

    <li
        id="{{template._id}}"
        class="template-box"
        type="template"
        ng-repeat="template in templates"
        ng-attr-draggable="dragSupported() === true"
    ></li>
    

    Demo

    JSFiddle

    This contains examples of usage for the following values: true, false, undefined, null, 1, 0, and "". Note how typically-falsey values may yield unexpected results.

    0 讨论(0)
提交回复
热议问题