0

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! :)

2 Answers 2

1

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

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

Comments

0

Your button should be in your directive template

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

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

    return {
        link: link,
        restrict: 'E',
        template: '<div><button class=btn btn-primary type="submit" ng-click="search()"></div>'
        scope: {data:'=',
        search:'&'}
    }

}]);

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.