将ng- *属性传递给Angular指令

时间:2015-01-08 20:45:06

标签: javascript angularjs

我有一个Angular指令<my-button>,我需要让它在它的输出上运行另一个指令(my-fun-directive),这就是为什么我使用$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>

当前输出(为了便于阅读而添加了换行符)

<button
    type="button"
    class="myCustomClass"
    ng-bind-html="buttonInnerHtml"
    my-fun-directive>
        <span class="glyphicon glyphicon-ok"><span> Save Changes
</button>

所需的输出(为了便于阅读而添加了换行符)

<button
    type="button"
    class="myCustomClass anotherClass"
    ng-bind-html="buttonInnerHtml"
    ng-hide="someProperty"
    ng-click="myClickEvent()"
    my-fun-directive
    example-directive>
        <span class="glyphicon glyphicon-ok"><span> Save Changes
</button>

请注意包含ng-*属性,附加指令和添加的CSS类。如何让所有这些一起工作?

1 个答案:

答案 0 :(得分:0)

问题出在buttonInnerHtml的HTML内容中。我收到错误“试图在安全的环境中使用不安全的值。”当我修复这一切时,一切正常:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
    </head>
    <body ng-app="plunker" ng-controller="MainCtrl">
        <my-button
            icon="ok"
            text="Save Changes"
            class="anotherClass"
            ng-hide="someProperty"
            ng-click="myClickEvent()"
            example-directive></my-button>
    </body>
    <script>
    var app = angular.module('plunker', []).directive('myButton', function ($compile, $sce) {
        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;
                scope.buttonInnerHtml = $sce.trustAsHtml(scope.buttonInnerHtml);
                var template = '<button type="button" class="myCustomClass" ng-bind-html="buttonInnerHtml" my-fun-directive></button>';

                var content = $compile(template)(scope);
                element.replaceWith(content);
            }
        };
    }).controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

    }]);
    </script>
</html>