Hans Daigle Hans Daigle - 3 months ago 10
AngularJS Question

How can I ng-click a function from my angular-js directive?

I cant figure how to call a function from my directive using ng-click.

This is an example of my HTML:

<div>
<directive-name data="exemple">
<button class=btn btn-primary type="submit" ng-click="search()">
</directive-name>
</div>


This is an example of my javascript :

...
.directive('directiveName', ['exempleService', function(exempleService) {
function link(scope, element, attrs) {

scope.search = function() {
console.log("this is working")
};
};

return {
link: link,
restrict: 'E',
scope: {data:'=',
search:'&'}
}

}]);


Thanks in advance! :)

Answer

You have to create a directive which includes the button inside the directive template (either as HTML or external file).

VIEW

<div ng-app="app">
  <directive-name data="exemple"></directive-name>
</div>

DIRECTIVE

var app = angular.module('app', [])

app.directive('directiveName', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.search = function() {
        alert('boe');
      }
    },
    template: '<button class=btn btn-primary type="submit" ng-click="search()">CLICK</button>'

  }
})

FIDDLE

Comments