Angularjs 中的条件 n- 包含

如何在 angularJS 中有条件地执行 ng- 包含?

例如,如果变量 x被设置为 true,那么我只想包含一些内容。

<div ng-include="/partial.html"></div>
76195 次浏览

If you are using Angular v1.1.5 or later, you can also use ng-if:

<div ng-if="x" ng-include="'/partial.html'"></div>

If you have any older version:

Use ng-switch:

<div ng-switch on="x">
<div ng-switch-when="true" ng-include="'/partial.html'"></div>
</div>

Fiddle

You could also do

<div ng-include="getInclude()"></div>

In your controller

$scope.getInclude = function(){
if(x){
return "partial.html";
}
return "";
}

If the condition is simple enough, you could also put the conditional logic directly in the ng-include expression:

<div ng-include="x && 'true-partial.html' || 'false-partial.html'"></div>

Note the expression x is not in single quotes and therefore evaluated. See http://plnkr.co/edit/4fvNDa6Gm3dbVLgsAZrA for more details.

A little bit more readable version of one of the answers. Plus setting ng-include to null removes the element - just like ng-if.

<div ng-include="x ? 'true-partial.html' : null"></div>

I encountered a similar issue and may be this finding can help someone. I have to display different partials on click of link but ng-if and ng-switch both were not working in this scenario(Below code was not working).

<button type="button" class="btn btn-link" ng-click="viewType('LIST')">List All</button>
<button type="button" class="btn btn-link" ng-click="viewType('EDIT')">Edit</button>
<button type="button" class="btn btn-link" ng-click="viewType('VIEW')">View</button>


<section class="col-md-8 left-col">
<span ng-if = "LIST">
<div data-ng-include="'./app/view/articles/listarticle.html'">
</span>
<span ng-if = "EDIT">
<div data-ng-include="'./app/view/articles/editorarticle.html'">
</span>


</section>

So what I did is, instead of using ng-if, On click of link just update the value of partialArticleUrl (which is a model in controller) and declare below code on html.

        <section class="col-md-8 left-col">
<div data-ng-include="partialArticleUrl">
</section>