Angular 页面丢失范围内包含多个 ngIncludes(?)

Angular Multiple ngIncludes with Transclusion on Page Losing Scope(?)

我正在尝试构建一个模块化的 ngInclude。通过这个,我的意思是 ngIncluded JSP 将引入它需要的所有依赖项并在渲染之前重新编译自身。

同一个文件在一个页面上多次使用。主页有几个选项卡 - 所有这些选项卡都使用这个 ngInclude 只是一些不同的查询字符串参数。此外,在每一页上,我都有一个包含文件的 "preview" 版本,然后当他们单击预览时会弹出一个模式,它再次 ngIncludes 相同的文件,但有另一个查询字符串参数将其放入编辑模式。

除了 IE9 (gah),我已经让它在任何地方都能正常工作,当然,我必须支持 IE9 并且必须重构所有内容。因为想要使这个 ngInclude 模块化并让它包含所有自己的依赖项,所以每次它被 ngIncluded 时它都会再次引入那些相同的依赖项。这在更优雅地处理它的更现代的浏览器中很好,但在 IE9 中它会爆炸 multiple directives asking for templatemultiple directives asking for transclusion。我能找到的唯一适用于我的情况的线索表明,这是因为依赖项被多次拉入。而且,到目前为止,我已经能够开始工作,我已经确认情况似乎是这样。

所以,我来了。我试图通过只引入一次依赖项(使用 RequireJS)来完成这项工作。我没有使用路线。我让它在初始页面加载时工作,但是一旦我更改选项卡或打开编辑模式(这两个操作都会导致另一个 ngInclude),我什么也得不到。我真的得到了一个空白页。

我已经输入了 console.logs 并且可以看到操作顺序是应该的(点击我的重新编译指令,它会一直执行 $compile 然后内部指令被命中)。我还可以使用浏览器控制台访问 $('selectorForController').scope().items$('selectorForController').scope().params 并确认它们具有我期望的数据。问题是由于某种原因视图没有更新(这是我期望 $compile 触发的)。

应用定义:

var providers = {};
var myApp = angular.module('myApp', ['ngSanitize', 'ngAnimate', 'ngResource', 'pascalprecht.translate', 'angularFileUpload', function($controllerProvider, $compileProvider, $provide) {
    providers = {
        $controllerProvider : $controllerProvider,
        $compileProvider : $compileProvider,
        $provide : $provide
    };
}]);
var queueLen = myApp._invokeQueue.length;

ngIncluded JSP:

<jsp:include page="profileIncludeListTemplate.jsp"/> <%-- Contains the profileItemList.jsp ng-template --%>
<jsp:include page="profileIncludePanelTemplate.jsp"/> <%-- Contains the profileItemPageRightPanel.jsp ng-template --%>

<script type="text/javascript">
    // Define itemsData and params here
</script>

<%-- One of my iterations was trying to use a directive I called lazyscript to load in all of the dependencies and then recompile, but that didn't work --%>
<%--<lazyscript data-src="/assets/js/profile/profileItemPageService.js"></lazyscript>--%>
<%--<lazyscript data-src="/assets/js/profile/profileItemService.js"></lazyscript>--%>
<%--<lazyscript data-src="/assets/js/profile/profileIncludeController.js"></lazyscript>--%>
<%--<lazyscript data-src="/assets/js/profile/profileIncludeDirectives.js"></lazyscript>--%>

<%-- Another iteration was trying to get it to work this way, where I also wrote a directive to overload the default script tag and recompile if necessary, but that didn't work either --%>
<%--<script src="/assets/js/profile/profileItemPageService.js" type="text/javascript"></script>--%>
<%--<script src="/assets/js/profile/profileItemService.js" type="text/javascript"></script>--%>
<%--<script src="/assets/js/profile/profileIncludeDirectives.js" type="text/javascript"></script>--%>
<%--<script src="/assets/js/profile/profileIncludeController.js" type="text/javascript"></script>--%>

<%-- I can't define the ngController here because it will throw an error on initial load and stop the rest of the execution, so I have the recompile apply it --%>
<%-- So I ultimately settled on this, which defines which dependencies need to be pulled in so that I can hand that list to Require --%>
<div
    data-recompile
    data-recompile-controller="ProfileIncludeCtrl"
    data-recompile-dependencies="/assets/js/profile/profileItemPageService.js,/assets/js/profile/profileItemService.js,/assets/js/profile/profileIncludeController.js,/assets/js/profile/profileIncludeDirectives.js"
    data-recompile-finished="false"
    class="profile-include"
    data-ng-class="{'form-horizontal': !params.edit}">

    <profile-item-list-directive></profile-item-list-directive>
    <profile-item-page-right-panel-directive></profile-item-page-right-panel-directive>
</div>

重新编译指令:

myApp.directive('recompile', function($window, $q) {
    return {
        restrict: 'A',
        link: function ($scope, elem, attrs) {
            if($(elem).attr('data-recompile-finished') == 'true') return;
            var dependencies = $(elem).attr('data-recompile-dependencies').split(',');

            function recompiler() {
                $(elem).attr('data-recompile-finished', 'true');
                $(elem).attr('data-ng-controller', $(elem).attr('data-recompile-controller')); // Link the angular controller

                var queue = myApp._invokeQueue;
                for (var i = queueLen; i < queue.length; i++) {
                    var call = queue[i];
                    var provider = providers[call[0]];
                    if (provider) {
                        provider[call[1]].apply(provider, call[2]);
                    }
                }

                if ($('[data-ng-app="myApp"]').injector()) {
                    $('[data-ng-app="myApp"]').injector().invoke(function ($compile, $rootScope) {
                        $compile($(elem))($rootScope);
                    });
                }
            }

            requirejs(dependencies, recompiler);
        }
    };
});

外部控制器的相关部分(在profileIncludeController.js中定义):

myApp.controller('ProfileIncludeCtrl', function($scope, $rootScope, $resource, $timeout, ProfileItemService, ProfileItemPageService) {
    $scope.items = [];
    $scope.params = [];

    $scope.params = buildParamsObject(params);
    $scope.items = itemsData.data || [];
});

指令的相关部分(在 profileIncludeDirectives.js 中定义)。这些指令被包含在内,因为它们需要能够访问彼此的范围以及 ProfileIncludeCtrl 中的某些函数,因为这些函数实际上并不属于任何一个指令。

myApp.directive('profileItemListDirective', function($rootScope, $timeout) {
    return {
        restrict : 'E',
        templateUrl : 'profileItemList.jsp',
        replace: true,
        transclude : true,
        scope : true,
        controller : function($scope, ProfileItemService, ProfileItemPageService) {
            console.log("listDirective controller");
        },
        link : function($scope, element, attrs) {
            console.log("listDirective link");
        }
    };
});

myApp.directive('profileItemPageRightPanelDirective', function($rootScope, $timeout) {
    return {
        restrict : 'E',
        templateUrl : 'profileItemPageRightPanel.jsp',
        replace: true,
        transclude : true,
        scope : true,
        controller : function($scope, ProfileItemService, ProfileItemPageService) {
            console.log("panelDirective controller");
        },
        link : function($scope, element, attrs) {
            console.log("panelDirective link");
            // $scope.params is not defined here, but I need and expect it to be
        }
    };
});

如有任何指导,我们将不胜感激!

事实证明,我可以通过稍微更改重新编译功能来修复它。使用 $controller 服务并将 $ngControllerController 数据属性放在 children 上是实现它的主要思想。

function recompiler() {
    var ctrl = $elem.attr('data-recompile-controller');
    $elem.attr('data-ng-controller', ctrl); // This is for aesthetics only

    $elem.removeAttr("data-recompile")
            .removeAttr("recompile")
            .removeAttr("data-recompile-controller")
            .removeAttr("recompile-controller")
            .removeAttr("data-recompile-dependencies")
            .removeAttr("recompile-dependencies");

    var queue = myApp._invokeQueue;
    for (var i = 0; i < queue.length; i++) {
        var call = queue[i];
        var provider = providers[call[0]];
        if (provider) {
            provider[call[1]].apply(provider, call[2]);
        }
    }

    var templateCtrl = $controller( ctrl, { $scope: $scope } );
    $elem.children().data('$ngControllerController', templateCtrl);
    $compile( $elem.contents() )( $scope );
}