1

I can't seem to reach the link function scope variable from inside a function in my directive. The "elem" variable is defined, but the scope isn't. Why is that??

Here's my directive:

function contextMenu($document){
  return {
    scope: {
      target: '=',
    },
    restrict: 'A',
    link: function(scope, elem, attr) {
      elem.bind('contextmenu',handleRightClick);
      function handleRightClick(event) {
        // do something with scope (scope is undefined)
      }
    }
  }
};

How can I user the scope variable?

Thanks!

Uri

EDIT1:

I found I can use this to pass the scope to the function: Passing parameters to click() & bind() event in jquery?, but this still doesn't explain why the scope variable is undefined.

EDIT2:

For completeness sake, this is how my directive is set up:

app.js

angular
  .module('myModule', [])
  .directive('contextMenu', ['$document', components.contextMenu])

and in the html:

<div context-menu target="testObject">

3
  • Is there a reason why u r not using ng-click? Commented Feb 4, 2015 at 8:52
  • scope should be accessible. Do a console log of scope and check. Giving breakpoint inside function and verifying for scope might be undefined. Commented Feb 4, 2015 at 8:56
  • I've checked, it's undefined Commented Feb 4, 2015 at 9:08

1 Answer 1

0

Make sure you are using the directive correctly. Since you didn't include the use of the directive in your template, I hope you used it something like this:

    <div context-menu target="something"></div>

Then I am confused about the setup of your directive. Try this:

    MyDirectiveModule.directive('contextMenu', function(){
        return {
            restrict: 'A',
            scope: {
                target: '@'
            },
            link: function(scope, element){
                console.log(scope);
                // don't use $scope!
            }
        };
    });

Make sure to use scope instead of $scope in the link: part.

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

4 Comments

Thanks, I added the directive setup code. And, yes, i'm using scope and not $scope.
can you make a plunkr?
I tried recreating in a plunkr but it won't re create. The actual directive is nested inside some other directives in a bit of a complicated structure. Anyway, thanks for the help, if i'll manage to recreate i'll update the question.
Okay, maybe the complicated setup was the problem then? Good luck to you!

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.