0

so I have an example custom directives code

angular.module('myApp.directives', []).
            directive('exampleDirective', ['version', function(version) {
             return {
                      link:function(scope,elm,attr) {
                         elm.on('click',function() {
                              alert("clicked element")
                         });
                      }
                    }
            }]);

and this is the markup html that I made

   <example-directive></example-directive>
   <button ng-click="click()">click me</button>

as you can see the button is outside the example-directive environment and as you can see the ng-click is defined and throw the click() function into controller.

my question is how can I get the alret("clicked element") from custom directive when I clicked the ng-click button in angularjs ?

2
  • You can't with what you have. You have two different scopes. Commented Jul 4, 2014 at 4:27
  • yap isolated scope on the custom directives if I'm not mistaken.. so there isn't another way with the approach that I wrote above? Commented Jul 4, 2014 at 4:45

1 Answer 1

3

Try it like this:

plunker

app.directive('exampleDirective', function() {
  return {
    restrict: 'E',
    link:function(scope,elm,attr) {
       scope.clicky = function(){console.log('clicked')};
    }
  }
});

Since we aren't creating a new scope with the directive, both the scope referred in the linking function of the directive and the one inferred by ng-click (which is another directive that comes with angular) will be the same scope, in this case the $rootScope.

Note that you need to add restrict: 'E' for the directive to work on what you wrote. The default value for that is by attribute (E is for element name) so it would work without it if you had <div example-directive />

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

1 Comment

I tried your plunkr and the button is inside the directive container if I'm not mistaken.. well is there a way with my approach above ? because my project mockup is set to be like that..

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.