Angularjs - 使用指令添加 ng-* 属性

标签 angularjs angularjs-directive

我正在尝试向指令管理的元素添加简单的 ng-mouseover 绑定(bind)。但是colud没有让它工作。

@ http://jsbin.com/aqibij/2/edit

添加 ng-mouseover 绑定(bind)后,我尝试重新编译元素。 directive.compile 和外部 Controller 运行,但directive.linker 不运行。

@ http://jsbin.com/ikebed/1/edit

我已将 $compile'ing 移到链接器中。它运行良好,ng-mouseover 运行良好,但在链接器中重新编译会导致无限循环,最终导致浏览器崩溃:)

如何使用指令将 ng-* 绑定(bind)添加到元素?我在这些方法中做错了什么?

最佳答案

我以为你和我在同一条船上,但也许你不是。无论哪种方式,这里有两个解决方案。我被困在第二个。

1) 特定元素指令

如果您知道您正在处理的元素将是 div、span、h1 等等 - 或者没关系(取一个元素并将其替换为您需要的元素)。

HTML

<div data-mydirective>
    <span>some other stuff</span>
    <div>more stuff</div>
</div>

指示
module.directive( 'mydirective', [ function() {
    return {
        restrict: "A",
        controller: function( $scope ) {
            $scope.test = function() {
                console.log('howdy');
            }
        },
        template: "<div data-ng-transclude data-ng-mouseover='test()'></div>",
        transclude: true,
        replace: true,
        link: function ( scope, element, attrs ) {

        }
    };
}]);

输出
<div ng-mouseover="test()" data-ng-transclude="" data-mydirective="">
    <span class="ng-scope">some other stuff</span>
    <div class="ng-scope">more stuff</div>
</div>

2) 针对非特定元素的指令

这是我面临的问题。基本上,如果您有一个可能位于 h1、h2、span、div、nav 等上的指令,并且您想添加您的 ng-*和指令中的属性。

您不能使用 template因为你不知道元素是什么。不想拍h1并将其替换为 div对?这就是我走编译路线的原因。好吧,template实际上可以是一个我们可以访问的函数elementattrs .

指示
module.directive( 'mydirective', [ function() {
    return {
        restrict: "A",
        controller: function( $scope ) {
            $scope.test = function() {
                console.log('howdy');
            }
        },
        template: function( element, attrs ) {
            var tag = element[0].nodeName;
            return "<"+tag+" data-ng-transclude data-ng-mouseover='test()></"+tag+">";
        },
        transclude: true,
        replace: true,
        link: function ( scope, element, attrs ) {

        }       
    }   
}]);

HTML/输出

和上面一样。更改div将 HTML 中的元素转换为 nav ,并且输出将反射(reflect)更改。

关于Angularjs - 使用指令添加 ng-* 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18206809/

相关文章:

angularjs:是否可以从 self 指令编译函数访问指令名称?

javascript - 未调用 Angular 指令的链接函数

javascript - bs-工具提示类型错误 : Cannot read property 'nodeName' of undefined

javascript - 使用双花​​括号输入指令不起作用

angularjs - UI-Router 不会从 URL 正确状态

javascript - 如何在数据格式的 ng-repeat 中使用 order 和 group by

javascript - 最好通过 ng-app 指令或 .config Controller 属性应用 Controller

javascript - 两个不同文件中的 Angular 指令 : only one will appear in the view

javascript - ng-重复 : Identify Change of Element Value In Sorted List

javascript - 在 ng-repeat 中使用 ng-model