0

I have a page with 2 containers on it , each one contains images. I want to add some specific visual attributes and functionalities to these images. These specific stuff is similar in both depositories but it is not the same. So i want to create one directive for 2 types of images , but i want it to behaviour a little bit differently depending on in what depository ( actually, scope ) image is placed. Checking for element's scope in directive's body:

studio.directive('orientable', function () {
    return {
        link: function(scope, element, attrs) {
              if(scope.id=="Depository1"){ 
              // give to element some specific behaviour
              }else if(scope.id=="Depository2"){ 
              // give to element another specific behaviour
              }
    }    
}

seems ugly to me.
I can't use passing arguments to a directive, because then image's tag will turn to unreadable and when there are many images it will be disaster . I do not want two directives because they will be basically same.
So i want one directive , but somehow it must be "polymorphic". Is it some kind of inheritance possible here? I think i'm missing something important in understanding of Angular' directives .

2
  • why not attributes that can be passed as parameteres to the directive? stackoverflow.com/questions/13725938/… in any case, your directive should probably have scope:true. otherwise, two orientable will be sharing things Commented Jul 11, 2013 at 11:17
  • @EduardGamonal Then it will be too much DRY in my html code , and i think its bad for performance too Commented Jul 11, 2013 at 11:33

1 Answer 1

0

If you want a single directive to behave differently based on scope, then checking some scope property seems perfectly reasonable to me.

The closest I think you can come to polymorphism in Angular is to put shared things (data, functions, etc.) into a service, then inject that service into the places you want polymorphism (directives, controllers, other services, etc.).

Sign up to request clarification or add additional context in comments.

2 Comments

Oh , i think i get it. I need to check a scope for some more global properties , like "isDragEnabled" and not for scope's "id" , so directive will stay more generic and not case-specific, right?
@Cherniv, yes, check for some property on the scope that would make sense for the directive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.