首页 > 解决方案 > 来自根控制器的 ng-include html 模板中的 ng-if 问题

问题描述

我来自 Angular9 并且真的习惯了它,我被要求在一个我从未经历过的 AngularJS 项目上工作一点。所以我真的在整个应用程序结构上苦苦挣扎。我的问题很简单:我有一个 sub-navbar.html 模板使用 ng-include 直接注入到我的 root.html 模板中,我想使用 'ng-if' 来调节该子导航栏的一个部分的显示(不只是隐藏该部分,我根本不希望它在那里)。我有一个后端调用,它根据连接的用户是否可以看到该部分向我发送一个布尔值。

我遇到的问题是,即使布尔值为“真”,我的部分实际上也从未处于活动状态。

我尝试过的事情:

不幸的是,我无法复制我所有的代码,但这里是我正在处理的主要部分:

app.js:(我在 '.run()' 函数中没有写任何关于这个 '$rootScope.adminSection' 的内容,并且还尝试了相同的方法直接调用没有 '$onInit' 的服务)

    $urlRouterProvider.otherwise("/orders");
    $stateProvider
        .state('root', {
          abstract: true,
            url: '',
            views: {
                '': {
                    templateUrl: "view/root.html",
                    controller: ['$rootScope', 'AdministratorService', function ($rootScope, AdministratorService) {
                        const vm = this;
                        vm.$onInit = function() {
                            AdministratorService.getAdminSection().then(function (result) {
                                    $rootScope.adminSection = result;
                                }
                            )
                        };
                    }]
                }

}])

根.html:

<div ui-view="root_header"></div>
 <div class="row" style="min-height: 600px">
    <div class="col-md-2">
        <br/>
        <div ng-include="'view/subnavbar.html'"></div>
    </div>
        <div class="col-md-10">
        <div ui-view></div>
    </div>
</div>
    <div ng-include="'view/footer.html'"></div>

subnavbar.html:

<ul class="nav nav-pills nav-stacked" role="tablist">
        <li></li>
        <li ui-sref-active="active"><a ui-sref="root.contracts"></a><div class='arrow' aria-hidden='true'></div>
    </li>
    <li ng-if="$rootScope.adminSection" ui-sref-active="active"><a ui-sref="root.administrator">
    </a><div class='arrow' aria-hidden='true'></div></li>
    
        <li ui-sref-active="active"><a ui-sref="root.users"></a><div class='arrow' aria-hidden='true'>
    </div></li>
    </ul>

欢迎任何帮助,在此先感谢!

标签: javascripthtmlangularjs

解决方案


有几种方法可以工作。它现在不起作用的原因是模板中的 $rootScope 没有定义。尝试在您的模板中替换$rootScope.adminSectionadminSection.

ngInclude 指令创建一个继承自$rootScope. 因此,变量 in$rootScope应该可以直接从模板访问。


推荐阅读