alecbz
alecbz

Reputation: 6488

Utility functions for directives

Say I want to make an angular directive that generates links to resources that look like this:

<a href="http://link/to/resource/1234">link/to/resource/1234</a>

from an object that looks like:

resource = {
  id: 1234,
  otherProperty: 'foo'
}

How can I do this effectively w/ a directive? Ie, I'd like to not have to repeat the part that goes '/link/to/resource/{{id}}'. I can't seem to get that to work right. One of the several things I've tried:

app.directive('myResource', function() {
  return {
    restrict: 'E',
    scope: {
      resource: '='
    },
    baseUrl: 'link/to/{{resource.id}}',
    template: '<a href="http://{{baseUrl}}">{{baseUrl}}</a>'
  };
});

which ends up rendering:

<a href="http://" class="ng-binding"></a>

Other things I've tried (like making baseUrl a function/sticking it in scope) have resulted in similar things/errors.

Is there a way to get something like this to work?

Upvotes: 2

Views: 517

Answers (2)

mpm
mpm

Reputation: 20155

just write a directive controller

app.directive('myResource', function() {
  return {
    restrict: 'E',
    scope: {
      resource: '='
    },
    controller: function($scope){
      $scope.getBaseUrl = function(resource){
         return 'link/to/'+resource.Id;
      };
    },
    template: '<a ng-href="http://{{getBaseUrl(resource)}}">{{getBaseUrl(resource)}}</a>'
  };
});

a function makes more sense,because you wont have manage resource state change.You may answer that the Id is unlikely to change but in my opinion,it's better practice in general.

http://plnkr.co/edit/I2QKNB1o8jvZf7kCDT2v?p=preview

Upvotes: 1

KayakDave
KayakDave

Reputation: 24676

One way to handle this is to use the directive's link function to set the variable up for you, like this:

link: function(scope) {
  scope.baseUrl= 'link/to/'+scope.resource.id;
},
template: '<a href="http://{{baseUrl}}">{{baseUrl}}</a>'

Here's a working fiddle

Alternatively you could use this approach:

link: function(scope) {
  scope.baseUrl= 'link/to/';
},
  template: '<a href="http://{{baseUrl}}{{resource.id}}">{{baseUrl}}{{resource.id}}</a>

Here's the fiddle

Upvotes: 3

Related Questions