Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs Custom Directive ng-click not working

Tags:

angularjs

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

like image 881
Yonatan Naxon Avatar asked Dec 12 '14 09:12

Yonatan Naxon


2 Answers

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/

like image 194
Ashesh Avatar answered Oct 30 '22 04:10

Ashesh


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',
  }
})
like image 35
VK321 Avatar answered Oct 30 '22 03:10

VK321