Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive Callback

Tags:

I would like to send a call back into a directive via a parameter on the tag, and then call that method when appropriate inside the directive. For example, when a button was clicked call a method on the parent controller.

I have a simple plunker of it not working

html file:

<body ng-controller="ParentController">
    <h1> Method Arguments </h1>
    <h3> open console to view output</h3>
    <hello-world onLoadCallback="myCallback(arg1)"></hello-world>
</body>

javascript file:

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

function ParentController($scope) {
  $scope.myCallback = function(var1){
    console.log("myCallback", var1);
  }
}
app.directive('helloWorld', function() {
  return {
      restrict: 'AE',
      template: '<h3>Hello World!!</h3>',
      scope:{
            onLoadCallback: '&'
        },
        link: function(scope, element, attrs, dateTimeController) {
            console.log('linked directive, not calling callback')
            scope.onLoadCallback('wtf');

      }
  };
});
like image 571
nakkor Avatar asked Jul 08 '14 19:07

nakkor


People also ask

What is directive in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What is restrict in AngularJS directive?

Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name.

What is custom directive in AngularJS?

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.


1 Answers

Tricky tricky angular, when declaring the argument in the HTML, it needs to use snake case, instead of camelcase to match.

Works:

<hello-world on-load-callback="myCallback(arg1)"></hello-world>

Doesn't Work:

<hello-world onLoadCallback="myCallback(arg1)"></hello-world>
like image 57
nakkor Avatar answered Oct 24 '22 06:10

nakkor