我在include中有一个模板。我在同一页面的2个单独的实例中使用它。如何有条件地显示其中的信息?
代码:
var myApp = angular.module("myApp", []);
myApp.controller("main", function($scope) {
$scope.firstTitle = true;
$scope.secondTitle = true;
});
html:
<div ng-controller="main">
<div class="show-first">
Your first info is :
<ng-include src="'info.html'"></ng-include>
//only need to show first tittle
</div>
<div class="show-second">
Your second info is:
<ng-include src="'info.html'"></ng-include>
//only need to show second tittle
</div>
</div>
<script type="text/ng-template" id="info.html">
<div>
<h1 ng-if="firstTitle">Info to show in first </h1>
<h1 ng-if="secondTitle">Infor to show in second </h1>
</div>
</script>
答案 0 :(得分:2)
如果要根据特定值/条件显示/隐藏组件段。您也可以遵循这种方法。
<div ng-show="isSectionShown()">
<h3>First Section Title</h3>
<div> Section Contents </div>
</div>
<div ng-show="isSectionShown()">
<h3>Second Section Title</h3>
<div> Section Contents </div>
</div>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.selectedSection = 'First';
$scope.isSectionShown = function() {
// This is for demonstration only, you can come with your implementation here to allow multiple checkings
return angular.equals($scope.selectedSection, 'First');
}
});
使用类似的条件细分,您可以使用ng-show, ng-hide, ng-if
类似的语句。
答案 1 :(得分:0)
分别使用两个控制器来控制模板的显示:Plunker。
.controller("oneCtrl", function($scope) {
$scope.firstTitle = true;
$scope.secondTitle = false;
}).controller("twoCtrl", function($scope) {
$scope.firstTitle = false;
$scope.secondTitle = true;
})
答案 2 :(得分:0)
要解决此问题,请将模板分开。
<script type="text/ng-template id="info1.html">
<div>
<h1 ng-if="firstTitle">Info to show in first </h1>
</div>
</script>
<script type="text/ng-template id="info2.html">
<div>
<h1 ng-if="secondTitle">Info to show in second </h1>
</div>
</script>
唯一的另一个选择是从不同的控制器访问它,这样你可以关闭一个,另一个打开。分离模板是最通用的选择IMO。