AngularJS - Use attribute directive conditionally

前端 未结 4 1591
走了就别回头了
走了就别回头了 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: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

    • {{$parent.x}}

    Controller

    function Ctl($scope) {
       $scope.checkPermissions = function(idx) {
         // do whatever you need to check permissions
         // return true to add the attribute
       }
    }
    

提交回复
热议问题