如何修改没有容器元素的条件显示指令

时间:2015-08-03 17:43:32

标签: javascript html angularjs angularjs-directive

我在angularjs中开发了一个简单的基于角色的安全指令。这是我的第一个指令。我想要做的就是替换这个HTML:

Hello WORLD!!!! {{name}}

用这个:

var securityModule = angular.module('securityModule', []);

securityModule.factory('security', function($http, $log) {
    var privileges = ['GET_ME', 'GET_POSTS'];

    return {
        hasPrivilege: function(privilege) {
            for (var i = 0; i < privileges.length; i++) {
                if (privileges[i] === privilege) {
                    return true;
                }
            }
            return false;
        }
    };
});

securityModule.directive('authorize', function(security, $log) {
    var directive = {};

    directive.restrict = 'EA';
    directive.transclude = true;
    directive.template = '<div ng-show="isAllowed" ng-transclude></div>';
    directive.scope = {};
    directive.replace = true;

    directive.link = function (scope, element, attrs) {
        $log.info(attrs.ifGranted);

        scope.isAllowed = security.hasPrivilege(attrs.ifGranted);
    };

    return directive;
});

如果用户具有GET_POSTS权限。否则,我想完全从DOM中删除元素。我的指令定义如下:

<div ng-show="isAllowed" ng-transclude="" if-granted="GET_POSTS" class="ng-isolate-scope">
    <span class="ng-binding ng-scope">
        Hello WORLD!!!! Serdar Kuzucu
    </span>
</div>

但是,这将使用以下HTML替换指令标记:

ng-show

我不想看到这个div和span标签。我只想看到指令的内容。

另外,我不想使用beginUpdates/endUpdates。相反,我想删除元素。

如何修改指令?

感谢。

1 个答案:

答案 0 :(得分:0)

要从DOM添加和删除元素,您可以使用ng-if代替ng-show而不是ng-if<div ng-if="isAllowed" if-granted="GET_POSTS" class="ng-isolate-scope"> <span class="ng-binding ng-scope"> Hello WORLD!!!! Serdar Kuzucu </span> </div> 将根据在其属性值中计算的表达式添加/删除。

<强>标记

// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000);  // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000);  // Let the user actually see something!
driver.quit();

Working Plunkr