如何从AngularJS中编译获得承诺?

时间:2013-12-17 16:37:44

标签: javascript angularjs

编译完成后需要触发一个事件。

这是我的父控制器的样子:

myApp.directive("ParentDirective", ["$rootScope", "$compile",
    function($rootScope, $compile) {
        return {
            link: function (scope, element) {
                var onClick = function () {
                    if (!scope.childDir) {
                        scope.childDir = $compile('<div ng-controller="childCtrl"/>')(scope);
                        $(scope.element).append(scope.childDir);
                    }
                    $rootScope.$broadcast('event');
                }

                $(element).click(onClick);
            }
        }
    }
]);

在childCtrl中我有一个监听器:

$rootScope.$on('event', doSomething);

问题是指令处理是在我的控制器触发事件​​之后发生的。有没有办法从编译器中获取承诺或在编译发生后以任何方式触发事件?

1 个答案:

答案 0 :(得分:0)

您可以在postLink功能中触发事件。试试吧。

compile: function compile(tElement, tAttrs, transclude) {
  return {
    pre: function preLink(scope, iElement, iAttrs, controller) { ... },
    post: function postLink(scope, iElement, iAttrs, controller) { 
        $rootScope.$broadcast('event'); 
    }
  }