Uri Klar Uri Klar - 1 year ago 112
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) {
function handleRightClick(event) {
// do something with scope (scope is undefined)

How can I user the scope variable?




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.


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


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

and in the html:

<div context-menu target="testObject">

Answer Source

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){
                // don't use $scope!

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download