How to useAttribute Binding in Angular
In this approach, we are using attribute binding to pass input to a custom directive in AngularJS. The directive is defined with restrict: ‘A’, and the input value is passed through the myDirective attribute. Within the directive’s link function, we watch for changes in the myDirective value and update the element’s text.
Syntax:
<div my-directive="name"></div>
Example: The below example uses Attribute Binding to pass input to a custom directive in AngularJS.
<!-- index.html -->
<!DOCTYPE html>
<head>
<title>Approach 1: Attribute Binding</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js">
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 style="color: green;">w3wiki</h1>
<h3>Approach 1: Using Attribute Binding</h3>
<input type="text" ng-model="name" placeholder="Enter your name">
<div my-directive="name"></div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.name = "";
});
app.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
scope.$watch('myDirective',function(newVal,oldVal){
if (newVal !== oldVal) {
element.text("Hello, " + newVal);
}
});
}
};
});
</script>
</body>
</html>
Output:
How to pass input to a custom directive in Angular JS?
In AngularJS, passing input to a custom directive allows the customization of components within an application. Directives can receive input via attributes, expressions, or controller functions, allowing for dynamic behavior and data binding.
In this article, we will explore two different approaches to pass input to a custom directive.
Table of Content
- Using Attribute Binding
- Using Services