Angularjs ng-click custom directive not working

I created a custom directive in angularjs:

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

Directive 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 compiling / link is the solution to this problem, but I cannot find a working solution.

I do not use jquery ..

+6
source share
2 answers

You need to add the link function to the directive definition for this. 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 html:

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

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

+10
source

Either use the link that @Ashesh responds to, or just add an area. If you set the area to false, you will not have a selection and clicking will work with the directive.

 directives.directive('myTop',function($compile) { return { restrict: 'EA', scope: false, templateUrl: 'views/header.html', } }) 
+1
source

Source: https://habr.com/ru/post/979493/


All Articles