【问题标题】:Use $compile inside Angular link function AND access directive arguements在 Angular 链接函数中使用 $compile 并访问指令参数
【发布时间】:2016-11-13 15:36:54
【问题描述】:

我正在 angular.js 1.x 中制作指令

我将指令调用如下:

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

我想通过在指令的链接函数中添加用于操作 DOM 的代码来创建指令。链接函数生成的DOM的结构依赖于dirarg的值,我希望一些元素有一个ng-click属性。

通过执行以下操作,我设法让 ng-clicks 起作用:

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

当我单击此指令生成的按钮时,函数testt() 运行。但是,如果我尝试访问 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));
        } 
    }
});

此代码现在使用 dirarg 填充按钮的文本,但 ng-click 功能中断。有人知道我如何让 ng-click 工作并访问指令的参数吗?

为了清楚起见,此按钮只是一个示例。我的实际情况比按钮复杂很多,所以不要告诉我更好的方法来制作有角度的按钮。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    在指令选项中添加作用域属性时,它使指令的作用域成为孤立的,你也需要在指令内部传递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));
            } 
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2017-01-28
      • 2015-05-02
      相关资源
      最近更新 更多