javascript - 来自根控制器的 ng-include html 模板中的 ng-if 问题
问题描述
我来自 Angular9 并且真的习惯了它,我被要求在一个我从未经历过的 AngularJS 项目上工作一点。所以我真的在整个应用程序结构上苦苦挣扎。我的问题很简单:我有一个 sub-navbar.html 模板使用 ng-include 直接注入到我的 root.html 模板中,我想使用 'ng-if' 来调节该子导航栏的一个部分的显示(不只是隐藏该部分,我根本不希望它在那里)。我有一个后端调用,它根据连接的用户是否可以看到该部分向我发送一个布尔值。
我遇到的问题是,即使布尔值为“真”,我的部分实际上也从未处于活动状态。
我尝试过的事情:
- 更改 ng-if 和 'ng-controller' 指令的优先级 ---> 破坏应用程序
- 添加一个新的 'subnavbar-controller' 并在 app.js 中将其声明为 .state ---> 不起作用
- 创建一个自定义指令 ---> 显然无法弄清楚工作原理,没有工作
不幸的是,我无法复制我所有的代码,但这里是我正在处理的主要部分:
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>
欢迎任何帮助,在此先感谢!
解决方案
有几种方法可以工作。它现在不起作用的原因是模板中的 $rootScope 没有定义。尝试在您的模板中替换$rootScope.adminSection
为adminSection
.
ngInclude 指令创建一个继承自$rootScope
. 因此,变量 in$rootScope
应该可以直接从模板访问。
推荐阅读
- php - 如何在其他 php 文件中使用 conexion 类?
- c++ - C++:通过函数参数传递的值给出不同的结果
- javascript - 如何为tone.js中正在播放的音符添加事件监听器
- vba - 初始化集合对象时出现 ActiveX 错误
- javascript - json2Csv Angular - 添加总计行
- javascript - 如何使用 jquery 或 javascript 隐藏空的 href 值按钮
- python - 我在给定的图像中找不到此问题的 Oython 代码?
- css - 如何将流体文本大小公式基于 rem 值?
- firebase - 如何让 Firebase.dart 中的 updateProfile 工作?
- c - 如何使用星星作为框架和内部的破折号创建一个框架框?