2

I have an angular directive (restrict to an element), its have an attribute to link to a function (using "&" attribute)

for example:

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
            myonclick: "&",
        },
        controller: 'myController',
        template: '<button ng-click="clicked()">Click me!</button>'
    }
}); 

i'm assigning a function to the attribute like this:

<my-directive myonclick="inScopeFunction()"></my-directive>

its work fine if the function is inside the angular controller scope. but i cant assign it to a function outside the angular scope.

there is a working example at plunker

Thanks

2 Answers 2

1

Since inScopeFunction() is a global method, you can call it directly inside your directive. Register a click listener on the element inside directive and call inScopeFunction() in listener callback. Here is the updated plunk

link: function postLink (scope, element, attrs) {
      element.on('click', function () {
        window[attrs.myonclick]()
      });
    }

html:

<my-directive myonclick="outScopeFunction"></my-directive>
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but i don't know the function inside the directive, and i want to get it an an attribute, to enable binding it each time to a different function
I have updated the plunk plnkr.co/edit/aCjMZ2QouLalRELPphwQ?p=preview. Please take a look.
0

Your controller will have access to global objects so you can access it from there

  $scope.inScopeFunction = outScopeFunction

To access it from your directive controller you could pass in a string and call the global object from there

<my-directive myonclick="'outScopeFunction'"></my-directive>
...
app.controller('myController', function($scope) {
  $scope.clicked = function(){
    window[$scope.myonclick()]()
    }
});

1 Comment

Its true, but i need the directive to call the function directly. Thanks any way

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.