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

3
  • 2
    alert is not working inside ng-click instead it will seach for $scope.alert function in the scope Commented Dec 12, 2014 at 9:54
  • originally I tried putting: $location.path('/') inside ng-click.. dosen't work Commented Dec 12, 2014 at 9:56
  • that is $location does not exist in the $scope Commented Dec 12, 2014 at 12:48

2 Answers 2

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/

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

4 Comments

What do you mean by native functions?
originally I tried putting: $location.path('/') inside ng-click.. doesn't work
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.
That worked for me but how can i attach a function that is already defined in the scope??
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',
  }
})

Comments

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.