How to pass parameters to directives in AngularJS



Image not found!!

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:

  1. 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.

    javascript
    angular.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 } }; });
  2. 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.
  3. Controller/Scope: If you want to dynamically set the values or functions, you can define them in your controller or scope.

    javascript
    angular.module('myApp', []) .controller('myController', function($scope) { $scope.value1 = 'Hello'; $scope.value2 = 'World'; $scope.myFunction = function() { alert('Button Clicked!'); }; });
  4. 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.