通过angularjs中的服务编译指令

时间:2013-07-11 18:36:13

标签: javascript angularjs angularjs-directive angular-services

我正在尝试通过角度服务编译指令,但不幸的是它不起作用。 这个想法是在弹出窗口中显示错误。

我修改了 $ exceptionHandler 服务:

crm.factory('$exceptionHandler', function(popup) {
    return function(exception) {
        popup.open({message: exception});
    }
});

弹出服务如下所示:

crm.factory('popup', function ($document) {
    return {
        open: function (data) {
            var injector = angular.element(document).injector(),
                $compile = injector.get('$compile'),
                template = angular.element('<popup></popup>');

            // var ctmp = $compile(template.contents());
            $compile(template.contents());

            $document.find('body').append(template);
        }
    };
});

我认为这不是硬代码 $ compile 服务的好主意(但我没有任何想法如何以角度实现这一点):

$compile = injector.get('$compile')

弹出式指令

crm.directive('popup', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/public/js/templates/common/popup.html',
        link: function() {
            console.log('link()');
        },
        controller: function () {
            console.log('ctrl()');
        }
    };
});

可能还有其他一些方法可以做到这一点吗? 感谢。

1 个答案:

答案 0 :(得分:1)

您可以将$compile直接注入您的服务,但您还没有正确使用$compile

//commented alternative lines for allowing injection and minification since reflection on the minified code won't work
//crm.factory('popup', ['$document', '$compile', function ($document, $compile) {
crm.factory('popup', function ($document, $compile) {
    return {
        open: function (data) {
            var template = angular.element('<popup></popup>'),
                compiled = $compile(template);

            $document.find('body').append(compiled);
        }
    };
});
//closing bracket for alternative definition that allows minification
//}]);