Uri Klar Uri Klar - 3 months ago 17
AngularJS Question

angular directive - scope undefined inside function

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">




Answer

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.