d4rty
d4rty

Reputation: 4188

Where to define a local function in a AngularJS Directive

Where do I have to define my function button() in the directive, such that pressing the button will trigger the function?

I don't want to use the outer scope of the app, I just want to use the local scope.

var app = angular.module("myApp", []);

app.directive('aaaa', function() {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      //this is not working: button: function(){console.log('hello from button');}
    },
    link: function(scope, element) {
      element.append('hello');
      element.append(' <button type="button" ng-click="button()">Click Me!</button> ')
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="myApp">

  <aaaa></aaaa>

</div>

Upvotes: 1

Views: 946

Answers (3)

Sander Ravenhorst
Sander Ravenhorst

Reputation: 169

I would advise to use angular templates instead of element.append, see example code below. Then you don't need all the compiler code 'n stuff.

You could also replace "template: 'hello

var app = angular.module("myApp", []);

app.directive('aaaa', function() {
  return {
    restrict: 'E',
    scope: {
      data: '='
    },
    link: function(scope, element) {
      scope.button = function(){
      console.log('hello from button');
      };
    },
    template: 'hello <button type="button" ng-click="button()">Click Me!</button>'
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="myApp">

  <aaaa></aaaa>

</div>

Upvotes: 0

digit
digit

Reputation: 4565

As @tymeJV said , you need to compile the html first and then call button() in directive controller

var app = angular.module("myApp", []);

app.directive('aaaa', function($compile) {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      //this is not working: button: function(){console.log('hello from button');}
    },
    link: function(scope, element) {
      element.append('hello');

     var htmlText = ' <button type="button" ng-click="button()">Click Me!</button> ';
      var template = angular.element($compile(htmlText)(scope));
      element.append(template);
    },
    controller: function($scope, $element){
       $scope.button = function(){
           console.log('button clicked');
       }
     }
  }
});

Upvotes: 2

Vikash Kumar
Vikash Kumar

Reputation: 1718

you can out under link

  link: function(scope, element) {
      element.append('hello');
      element.append(' <button type="button" ng-click="button()">Click Me!</button> ');
      scope.button=function(){
          //content goes here
      }
  }

Upvotes: -1

Related Questions