我遇到一些问题。我在一个父 Controller 中有一些嵌套 Controller ,我需要它使用 Angular.js 根据某些条件执行。我在下面解释我的代码。
NABH.html:
<div ng-controller=NABHParentController>
<div ng-show="showNabh">
<div ng-include="'nabh1.html'"></div>
</div>
<div ng-show="showNabh1">
<div ng-include="'nabh2.html'"></div>
</div>
</div>
nabh1.html:
<div class="right_panel" style="display:block;" id="auditnabh" ng-controller="NABHController">
<td class="sticky-cell" ng-click="initiateNABH(nabh.NABHAuditID)">
</td>
</div>
nabh2.html:
<div class="right_panel" ng-controller="NABH2Controller">
<h2 class="page-title">NABH (INT012017001)</h2>
<div>
NABHParentController.js:
var app=angular.module('demo');
app.controller('NABHParentController',function($scope,$http,$state,$window,$location,$filter){
$scope.showNabh=true;
$scope.showNabh1=false;
})
NABHController.js:
var app=angular.module('demo');
app.controller('NABHController',function($scope,$http,$state,$window,$location,$filter,getBothIdToAuditDetailPage)
{
$scope.initiateNABH = function(aid) {
$scope.$parent.$parent.showNabh=false;
$scope.$parent.$parent.showNabh1=true;
}
})
这里最初所有 Controller 都在加载,并且首先显示 nabh1.html
。当用户单击该 td click 事件时,将显示第二部分 html。在这里,我需要当用户单击 ng-click="initiateNABH(nabh.NABHAuditID)"
时,第二个 View 将打开,相应的 Controller 将开始执行。最初只会执行显示 View 相关的 Controller 。请帮忙。
最佳答案
听起来使用 ng-if
而不是 ng-show
可以解决您的问题:
<div ng-if="showNabh">
<div ng-include="'nabh1.html'"></div>
</div>
<div ng-if="showNabh1">
<div ng-include="'nabh2.html'"></div>
</div>
区别在于,当表达式为假时,ng-show将“仅”使用css隐藏元素,而如果表达式为假,ng-if将不会创建该元素,因此在ng-if之前不会启动 Controller 是真的。
另外,我可能会将 initateNABH 函数移至父 Controller - 它仍然可以在子 Controller 中使用,但由于您不必使用 $parent,因此代码不太可能被破坏:
var app=angular.module('demo');
app.controller('NABHParentController',function($scope,$http,$state,$window,$location,$filter){
$scope.showNabh=true;
$scope.showNabh1=false;
$scope.initiateNABH = function(aid) {
$scope.showNabh=false;
$scope.showNabh1=true;
}
})
关于javascript - 如何使用 Angular.js 根据特定条件加载 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054688/