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');
}
};
});
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With