In AngularJS, directives are a way to create reusable components and extend the functionality of HTML. You can pass parameters to directives using attributes in your HTML markup. Here's how you can achieve this:
Define the Directive:
First, define your directive with a scope
property to create an isolated scope for the directive. This allows you to pass parameters to the directive.
javascriptangular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
parameter1: '@', // for string binding
parameter2: '=', // for two-way binding
parameter3: '&' // for function binding
},
template: '<div>{{parameter1}}, {{parameter2}}, <button ng-click="parameter3()">Click me</button></div>',
link: function(scope, element, attrs) {
// Directive logic goes here
}
};
});
Use the Directive in HTML: In your HTML markup, you can now use the directive and pass parameters to it using attributes.
html<my-directive parameter1="value1" parameter2="value2" parameter3="myFunction()"></my-directive>
parameter1
: The value is passed as a string.parameter2
: The value is passed by reference for two-way binding.parameter3
: The value is passed as a function reference.Controller/Scope: If you want to dynamically set the values or functions, you can define them in your controller or scope.
javascriptangular.module('myApp', [])
.controller('myController', function($scope) {
$scope.value1 = 'Hello';
$scope.value2 = 'World';
$scope.myFunction = function() {
alert('Button Clicked!');
};
});
HTML Markup: Use the controller's scope values in your HTML markup.
html<div ng-controller="myController">
<my-directive parameter1="{{value1}}" parameter2="value2" parameter3="myFunction()"></my-directive>
</div>
This way, you can pass parameters to your AngularJS directives using attributes in the HTML markup and make your directives more flexible and reusable.