11

i've created a custom directive in angularjs:

directives.directive('myTop',function($compile) {
return {
    restrict: 'E',
    templateUrl: 'views/header.html',
}
})

Directive's code:

<div class="my-header">
<button ng-click="alert('x')" class="fa fa-chevron-left"></button>
<h1>SpeakZ</h1>
</div>

for some reason, ng-click doesen't trigger.

I searched over the internet and found that compile / link is the solution for this problem, but I can't seem to reach a working solution.

I am not using jquery..

Yonatan Naxon
  • 639
  • 1
  • 7
  • 25

2 Answers2

15

You'll need to add a link function to the directive definition for this to work. So basically,

var app = angular.module("myApp", [])

app.directive('myTop',function() {
return {
    restrict: 'E',
    template: '<button ng-click="clickFunc()">CLICK</button>',
    link: function (scope) {
        scope.clickFunc = function () {
            alert('Hello, world!');
        };
    }
}
})

And the html:

<div ng-app="myApp">
    <my-top></my-top>
</div>

And here's the fiddle: http://jsfiddle.net/4otpd8ah/

Ashesh
  • 2,978
  • 4
  • 27
  • 47
  • What do you mean by native functions? – Ashesh Dec 12 '14 at 10:03
  • originally I tried putting: $location.path('/') inside ng-click.. doesn't work – Yonatan Naxon Dec 12 '14 at 10:04
  • 1
    That will not work. You should have a function defined in the scope of the directive (in the case above its scope.clickFunc) which does something depending on what you'd need. `$location` will also need to be injected into the directive. – Ashesh Dec 12 '14 at 10:06
  • That worked for me but how can i attach a function that is already defined in the scope?? – pavan kumar Apr 02 '19 at 14:43
1

Either use link as answered by @Ashesh or just simply add scope. If you set scope false you will not have isolated scope and click will work on directive.

directives.directive('myTop',function($compile) {
return {
   restrict: 'EA',
   scope: false,
   templateUrl: 'views/header.html',
  }
})
VK321
  • 5,768
  • 3
  • 44
  • 47