I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field.
Current Implementation:
var myDirective = function () {
return {
restrict: 'E',
scope: {
items: '='
},
template:
"<div class='holder'>"
+ "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i class='fa fa-times'/>{{item.Name}}</a>"
+ "</div>",
controller: function ($scope) {......}
}
}
Desired Approach:
var myDirective = function () {
return {
restrict: 'E',
scope: {
items: '=',
display_field: 'Name',
icon_field: 'fa fa-times'
},
template:
"<div class='holder'>"
+ "<a data-ng-repeat='item in items' data-ng-click='myClick(item)'><i data-ng-class='{{item.icon_field}}'/>{{item.display_field}}</a>"
+ "</div>",
controller: function ($scope) {......}
}
}
Usage Example:
<my-directive items="myItems" display_field="OtherProperty" icon-field="iconProperty" />
Fiddle Demo: http://jsfiddle.net/1L7tdd1p/