简体   繁体   English

在Angular链接函数和访问指令争论中使用$ compile

[英]Use $compile inside Angular link function AND access directive arguements

I am making a directive in angular.js 1.x 我正在angular.js 1.x中创建指令

I call the directive as follows: 我将指令称为:

<mydirective dirarg={{value-1}}></mydirective>

I would like to create the directive by putting code to manipulate the DOM in the directive's link function. 我想通过在指令的链接函数中放置用于操作DOM的代码来创建指令。 The structure of the DOM generated by the link function is dependant on the value of dirarg, and I would like some elements to have a ng-click attribute. 链接函数生成的DOM的结构取决于dirarg的值,我希望某些元素具有ng-click属性。

I have managed to get ng-clicks to work by doing the following: 通过执行以下操作,我设法使ng-clicks起作用:

app.directive('calendar',function($compile){
    return{
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>hi</button>")(scope));
        } 
    }
});

When I click the button generated by this directive, the function testt() runs. 当我单击该指令生成的按钮时,函数testt()运行。 However, the call to testt() breaks if I try to access dirarg . 但是,如果我尝试访问dirarg ,对testt()的调用将中断。

app.directive('calendar',function($compile){
    return{
        scope:{
            dirarg: '@'
        },
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
        } 
    }
});

This code now populates the text of the button with dirarg, but the ng-click functionality breaks. 现在,此代码使用dirarg填充按钮的文本,但是ng-click功能中断。 Does somebody know how I can both have ng-click working, and access the arguments to the directive? 有人知道我如何才能同时执行ng-click和访问指令的参数吗?

To be clear, this button is just an example. 明确地说,此按钮只是一个示例。 My actual situation is a lot more complicated than a button, so don't tell me better ways to make buttons in angular. 我的实际情况比一个按钮要复杂得多,所以不要告诉我更好的方法来制作有角度的按钮。

When add scope property to directive option it makes isolated scope for directive, you need pass testt function inside directive too, or define testt function inside directive link functiontion 当将范围属性添加到指令选项时,它使指令成为隔离的范围,您也需要在指令内部传递testt函数,或在指令链接函数内部定义testt函数

<mydirective dirarg={{value-1}} testt="testt"></mydirective>

app.directive('calendar',function($compile){
    return{
        scope:{
            dirarg: '@',
            testt: '='

        },
        link: function(scope, element, attributes){
            element.append($compile("<button ng-click='testt()'>"+scope.dirarg+"</button>")(scope));
        } 
    }
});

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

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