dman dman - 1 year ago 138
AngularJS Question

Directive template - use attribute for html text interpolation?

Angular 1.*

I am using a directive to make my code drier... or attempting to. But because of variances in the json data structure, I am not sure it's possible because of the interpolation text for each radio button.

<ppv-filter filter-name="Region" radio-value="choice.code"
sort="description" filter-data="regions"></ppv-filter>
<ppv-filter filter-name="Market" display-prop="description"
<ppv-filter filter-name="Dealer" display-prop="code"

directive template:

<div ng-if="filterName === 'Region'">
<div ng-repeat="choice in filterData| orderBy: sort">
<input type="radio" value="{{choice.code}}" name="regionRadio">

<div ng-if="filterName === 'Market'">
<div ng-repeat="choice in filterData| orderBy: 'code'">
<input type="radio" name="bob">

<div ng-if="filterName === 'Dealer'">
<div ng-repeat="choice in filterData| orderBy">
<input type="radio" name="foo">

.directive('ppvFilter', ['regionMarketDealerSrv',
function(regionMarketDealerSrv) {
return {
templateUrl: 'app/ppv/ppv-filter.dir.html',
restrict: 'E',
scope: {
filterName: '@',
sort: '@',
radioValue: '@',
filterData: '='

Is it possible to pass a attribute binding to take the place, for example, of
? If not, then I am not really making my code drier by reusing a directive with so many code

Answer Source

I would create controller inside Your directive and inside it check properties sended to scope, in this particular example best would be switch statement. So in the switch set which param should be used in view.

( pseudo code in link or controller of directive )

switch (scope.filterName){

  case "Market":

  //other possibilities

Next in view we need only one structure by using array syntax [field].

 <div ng-repeat="choice in filterData| orderBy: 'code'">
  <input type="radio" name="bob">
  {{choice[field]}}<!-- HERE MOST IMPORTANT -->

I see that sorting also changes, so create second variable for sort type and assign it in the same switch in controller.

One more thing, directive attributes (props) assigned from parent scope can be used without any controller code, props are available in view, so it can be used in the same syntax like - {{someArr[filterName]}} where filterName was directive attribute.

Returning to Your problem - if we send by attribute name of property which should be used in view for example column:'@' and example value would be code,description then in view only {{choice[column]}} is needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download