1
votes

I'm just getting stared with Angular's directives, and while I could probably do this in-line in a template, I've committed to the notion of creating a directive for the following task...

I have a web app powered by a JSON API. I want a directive that will determine the source of a user's profile image (upload or social), do some string manipulation if it comes from Facebook, otherwise choose the appropriate image URL (large versus thumb) if it were an uploaded image for display.

The problem I'm having is with where to put this logic. I understand the general concept of directives, but don't know how to handle the conditional logic needed to make this happen.

Here's how I want put the large profile image in the view:

<lage-profile-image></large-profile-image>

Now here's the start of the directive including the template I want to return:

myApp.directive "largeProfileImage", ->
  restrict: 'E'
  replace: true
  template: "<img src=\"{{photoUrl}}\">"

Where would I put the following logic though? I don't necessarily need an isolate scope since there's one large profile image per page. But I can't figure out where the following logic goes - in the directive's link? in a the directive's controller? in the directive's scope? The following determines which URL to put into the template above...

  image_diplay = user.profile.image_display
  if image_display == "facebook"
    photoUrl = user.profile.avatar.replace(/\?type=square/, '?type=large')
  else
    photoUrl = user.profile.image.url

Where does this go in order to get the directive to work?

2

2 Answers

1
votes

You should place it inside link function

function link(scope) {
 var image_diplay = user.profile.image_display
   if (image_display == "facebook") {
     scope.photoUrl = user.profile.avatar.replace(/\?type=square/, '?type=large')
 } else {
     scope.photoUrl = user.profile.image.url
 }

Directive's controller - is primarily for comunication between directives.

0
votes

I would put it into directive controller so it might look something like this:

myApp.directive "largeProfileImage", ->
  restrict: 'E'
  replace: true
  template: "<img src=\'photoUrl\'>"
  controller: function($scope){
     image_diplay = user.profile.image_display
     if image_display == "facebook"
       $scope.photoUrl = user.profile.avatar.replace(/\?type=square/, '?type=large')
     else
       $scope.photoUrl = user.profile.image.url
  }

Anything that goes into link should about about manipulating DOM elements.