Javascript 将ng-*属性传递给角度指令

Javascript 将ng-*属性传递给角度指令,javascript,angularjs,Javascript,Angularjs,我有一个Angular指令,其中我需要让它在它的输出上运行另一个指令(my fun指令),这就是为什么我使用$compile而不是指令模板的原因。不幸的是,这样做似乎不允许传递任何额外的HTML属性或ng-*属性 指令 app.directive('myButton', function ($compile) { return { restrict: 'E', replace: true, scope: true, link

我有一个Angular指令
,其中我需要让它在它的输出上运行另一个指令(
my fun指令
),这就是为什么我使用
$compile
而不是指令模板的原因。不幸的是,这样做似乎不允许传递任何额外的HTML属性或
ng-*
属性

指令

app.directive('myButton', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        link: function (scope, element, attrs) {
            var btnTxt = attrs.text || "";
            scope.buttonInnerHtml = attrs.icon ? '<span class="glyphicon glyphicon-' + attrs.icon + '"></span> ' + btnTxt : btnTxt;
            var template = '<button type="button" class="myCustomClass" ng-bind-html="buttonInnerHtml" my-fun-directive></button>';

            var content = $compile(template)(scope);
            element.replaceWith(content);
        }
    };
});
<my-button
    icon="ok"
    text="Save Changes"
    class="anotherClass"
    ng-hide="someProperty"
    ng-click="myClickEvent()"
    example-directive></my-button>
app.directive('myButton',函数($compile){
返回{
限制:'E',
替换:正确,
范围:正确,
链接:函数(范围、元素、属性){
var btnTxt=attrs.text | |“”;
scope.buttonInnerHtml=attrs.icon?''+btnTxt:btnTxt;
var模板=“”;
变量内容=$compile(模板)(范围);
元素。替换为(内容);
}
};
});
用法

app.directive('myButton', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        link: function (scope, element, attrs) {
            var btnTxt = attrs.text || "";
            scope.buttonInnerHtml = attrs.icon ? '<span class="glyphicon glyphicon-' + attrs.icon + '"></span> ' + btnTxt : btnTxt;
            var template = '<button type="button" class="myCustomClass" ng-bind-html="buttonInnerHtml" my-fun-directive></button>';

            var content = $compile(template)(scope);
            element.replaceWith(content);
        }
    };
});
<my-button
    icon="ok"
    text="Save Changes"
    class="anotherClass"
    ng-hide="someProperty"
    ng-click="myClickEvent()"
    example-directive></my-button>

电流输出(为可读性增加了换行符)


保存更改
所需输出(为可读性增加了换行符)


保存更改

注意包含了
ng-*
属性、附加指令和添加的CSS类。我如何才能让所有这些都一起工作?

问题在于buttonInnerHtml的HTML内容。我收到错误“试图在安全上下文中使用不安全的值”。当我修复此问题时,一切正常:


var app=angular.module('plunker',[])。指令('myButton',函数($compile,$sce){
返回{
限制:'E',
替换:正确,
范围:正确,
链接:函数(范围、元素、属性){
var btnTxt=attrs.text | |“”;
scope.buttonInnerHtml=attrs.icon?''+btnTxt:btnTxt;
scope.buttonInnerHtml=$sce.trustAsHtml(scope.buttonInnerHtml);
var模板=“”;
变量内容=$compile(模板)(范围);
元素。替换为(内容);
}
};
}).controller('MainCtrl',['$scope','$http',函数($scope,$http){
}]);

你为什么说
,这就是为什么我使用$compile而不是指令模板?您可以在指令的template/templateUrl属性中声明一个指令。@ps0604是的,我知道,但我尝试使用的另一个指令在这样做时似乎不起作用。。。也许在我把它归咎于这个指令之前,我需要进一步研究一下另一个指令……你为什么不发布一个plunk?这应该行得通,你可能会遇到另一个问题。我本来打算这样做的,但经过更多的测试,我实际上确定我的问题与此完全无关&我能够以不同的方式解决它。