简体   繁体   English

AngularJS-如何为自定义指令设置CSS类?

[英]AngularJS - how to set css class for the custom directive?

Have tab css class for the nav html element which I'm going to use as directive like this: tab的CSS类nav这我会像这个指令使用HTML元素:

<nav tab></nav>

It expected to be interpreted like this: 期望这样解释:

<nav class="tab">
    <a></a>
    <a></a>
    <a></a>
</nav>

... and everything works almost as expected except of the issue I cannot set the CSS class to the top <nav> element. ...并且除了我无法将CSS类设置为顶部<nav>元素的问题之外,其他所有功能均按预期工作。 Of course, I could specify it using ng-class explicitly but it seems to be not a great idea. 当然,我可以使用ng-class明确指定它,但这似乎不是一个好主意。

Have heard about .addClass() option but it doesn't work at all: 听说过.addClass()选项,但它根本不起作用:

tab.directive('tab', function($compile) {
        return {
            restrict: 'A',
            templateUrl: 'nav-tab.html',
            controller: function($http, $scope) {
                $http.get('/Tab/List')
                    .success(function(data) {
                        $scope.tabs = data;
                    }).error(function() {
                        alert("error");
                    });
            },
            controllerAs: 'tab',
            link: function(element, scope) {
                angular.element(element).addClass('tab');
                $compile(element)(scope);
            }
        }
    }); 

How to add the CSS class to the top directive element without it's explicit specifying right at the element? 如何将CSS类添加到top指令元素,而无需在元素上明确指定?

You have a wrong sequence in link function 链接功能顺序错误

Instead of 代替

link: function(element, scope) {

Change it to 更改为

link: function(scope, element, attrs) {

Then you can directly do element.addClass as jQLite api has .addClass method available on it. 然后,您可以直接执行element.addClass因为jQLite api上具有.addClass方法。

I would change your directive to be an "element" ('E' instead of 'A' for attribute) 我会将您的指令更改为“元素”(属性使用“ E”代替“ A”)

<tab></tab>

tab.directive('tab', function($compile) {
return {
    restrict: 'E',
    templateUrl: 'nav-tab.html'...

and then add the class in your template nav-tab.html : 然后在您的模板nav-tab.html中添加该类:

<nav class="tab">
  <a></a>
  <a></a>
  <a></a>
</nav>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM