AngularJS广播$ routeChangeSuccess在指令中触发两次

时间:2016-05-24 23:00:19

标签: angularjs

我使用以下代码将路由更改广播到指令:

function run($rootScope) {
    $rootScope.$on('$routeChangeSuccess',
        function(event, current, previous, rejection) {
            if (current.$$route.originalPath !== '') {
                $rootScope.$broadcast(event.name, { loadedTemplateUrl: current.loadedTemplateUrl });
            }
        });
}

指令正在接收广播两次。该指令放在一个html模板上。没有控制器。如何防止在指令中触发两次?

    function optimizely($compile) {
    var directive = {
        restrict: 'E',
        link: function (scope, element) {
            scope.$on('$routeChangeSuccess',
                function (event, data) {
                    var template = '';

                    switch (data.loadedTemplateUrl) {
                        case '/app/views/china.html':
                            template = '<script src=""></script>';
                            break;
                        default:
                            template = '<script src="App/optimizelyTest.js"></script>';
                    }

                    scope.$apply(function () {
                        var content = $compile(template)(scope);
                        element.append(content);
                    });
                });
        }
    };

    return directive;
}

谢谢, 标记

0 个答案:

没有答案
相关问题