我现在正在开展一个项目,我们有几个不同的Tasks
,每个Task
都有自己的显示数据的方式,它们是不需要单独控制器的次要数据更改,和意见。
例如,一个任务可能有一个显示Username
的标题,下一个任务不需要用户名,而是用Behavior
替换它。
这就是我现在正在做的事情:
<div id="event-list">
<ul>
<li ng-click="isHidden=!isHidden;" ng-repeat="event in events" ng-init="isHidden=false;">
<!-- Template 1 -->
<div ng-if="taskCategory == 'taskExampleOne'">
<div class="heading">
<h1>{{event.EventName}}</h1>
<p class="description">Username: {{ event.User.Name }}</p>
<p class="date">{{ event.RecordDateUtc | moment: 'MM/DD/YYYY' }}</p>
</div>
<div ng-show="isHidden" class="body event-show-hide-animation">
<img src="{{ event.SnapshotJpg }}" />
<dl>
<dt>Record Date: </dt>
<dd>{{ event.RecordDateUtc | moment: 'MM/DD/YYYY HH:MM A' }} {{ event.RecordDateTz }}</dd>
</dl>
<button type="button" class="btn btn-primary" ng-click="viewEventDetails( event )">View Event</button>
</div>
</div>
<!-- End Template 1 -->
<!-- Template 2 -->
<div ng-if="taskCategory == 'taskExampleTwo'">
<div class="heading">
<h1>{{event.EventName}}</h1>
<p class="description">
<span>Username: {{ event.User.Name }}</span>
<span>Behavior: {{ event.BehaviorNames }}</span>
</p>
<p class="date">{{ event.RecordDateUtc | moment: 'MM/DD/YYYY' }}</p>
</div>
<div ng-show="isHidden" class="body event-show-hide-animation">
<dl>
<dt>Event: </dt>
<dd>{{ event.EventId }}</dd>
<dt>Group: </dt>
<dd>{{ event.QueryKey.GroupIds[0] }}</dd>
<dt>Record Date: </dt>
<dd>{{ event.RecordDateUtc | moment: 'MM/DD/YYYY HH:MM A' }} {{ event.RecordDateTz }}</dd>
</dl>
<button type="button" class="btn btn-primary" ng-click="viewEventDetails( event )">View Event</button>
</div>
</div>
<!-- End Template 2 -->
</li>
</ul>
</div>
因此,通过重复这些元素会产生相当多的浪费,但是我觉得它可以分解整个模板,而不是每条信息都有大量的ng-if
条件。 / p>
有没有更好的方法来处理这些模板?
答案 0 :(得分:1)
您可以使用create an angularjs指令。见Plnkr
您可以为两个待办事项创建一个模板,并使用ng-show / hide选择要呈现的元素,或为每个案例创建两个不同的指令。
myApp.directive("todo", function() {
return {
restrict: 'A',
templateUrl: "task.tpl.html"
};
});
注意文件模板todo.tpl.html
<div class="heading">
<h1>{{event.EventName}}</h1>
<p class="description">Username: {{ event.User.Name }}</p>
<span ng-show="event.BehaviorNames">Behavior: {{ event.BehaviorNames }}</span>
<p class="date">{{ event.RecordDateUtc | moment: 'MM/DD/YYYY' }}</p>
</div>
<div ng-show="!isHidden" class="body event-show-hide-animation">
<img src="{{ event.SnapshotJpg }}" />
<dl>
<dt ng-show="event.BehaviorNames">Event: </dt>
<dd ng-show="event.BehaviorNames">{{ event.EventId }}</dd>
<dt ng-show="event.BehaviorNames">Group: </dt>
<dd ng-show="event.BehaviorNames">{{ event.QueryKey.GroupIds[0] }}</dd>
<dt>Record Date: </dt>
<dd>{{ event.RecordDateUtc | moment: 'MM/DD/YYYY HH:MM A' }} {{ event.RecordDateTz }}</dd>
</dl>
<button type="button" class="btn btn-primary" ng-click="viewEventDetails( event )">View Event</button>
</div>
您可以阅读有关自定义指令enter link description here
的更多信息