Reputation: 1396
I have a simple ng-repeat
<div ng-repeat="obj in someArray"></div>
I would like to use the custom directive "type1" if obj.type == "type1"
and use the custom directive "type2" if obj.type == "type2"
. Is there a smart way to do that?
I will use this solution at different locations, so I would like to put the logic in the directive and not in the html. I was thinking that maybe I could use a "parent" directive that "includes" one directive or the other depending on obj.type
. What do you think?
Upvotes: 1
Views: 16512
Reputation: 1396
We can't attribute a function to templateUrl
in the current stable version (1.0.8), so here is what I did.
<div ng-controller="MainCtrl">
<div class="genericDirective" ng-repeat="obj in someArray"></div>
</div>
var app = angular.module("myApp", []);
app.controller("MainCtrl", function ($scope) {
$scope.someArray = [
{type:"type1",title:"lorem"},
{type:"type2",title:"ipsum"},
{type:"type2",title:"dolor"}
];
});
app.directive("genericDirective", function(){
return{
restrict: "C",
templateUrl: "genericDirective.html"
};
});
<div ng-include="thumb.type+'Thumb.html'"></div>
For some reason, I did not manage to nest directives, so I used ng-include
instead. (Edit: Problem solved here)
Upvotes: 0
Reputation: 3130
Depending on what you want, you can use ngClass for this.
<div ng-repeat="obj in someArray">
<div ng-class"{class1: obj.type == "type1", class2: obj.type == "type2"}"></div>
</div>
In this example, the object's type would apply a class. See http://docs.angularjs.org/api/ng.directive:ngClass for more information.
If this is to parse the data or something similar, you can try to use one directive, and handle the case inside.
Edit:
To expand on the later, you can put your logic in a service and call the appropriate functions in a parent directive. http://docs.angularjs.org/guide/dev_guide.services.creating_services
Upvotes: 3
Reputation: 4839
<div ng-repeat="obj in someArray">
<type1 ng-if="obj.type=='type1'"></type1>
<type2 ng-if="obj.type=='type2'"></type2>
</div>
In angular 1.2 you can use the ng-switch directive as well which is more efficient.
I guess I should add that the test might look more like this
ng-if="obj instanceof type1"
depending on what you mean by type.
Based on further comments I believe that this is also a possible answer to your question:
Angular Directive Different Template
Still, ng-if or ng-switch is a much easier way since it doesn't require any special knowledge of the ng-repeat object type.
Upvotes: 2
Reputation: 11078
Use ng-switch:
<div ng-repeat="obj in someArray">
<span ng-switch="obj.type">
<div directive-one ng-switch-when="type1"></div>
<div directive-two ng-switch-when="type2"></div>
</span>
</div>
Upvotes: 6