In this tutorial, I will be talking about how to manipulate DOM using jqLite. jqLite is a subset of jquery which allows angular to manipulate DOM. Let's start by creating the basic structure. Create two files described below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>AngularJS DOM manipulation with jqLite</title>
<link
rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-app="myApp">
<my-directive></my-directive>
</div>
</body>
</html>
'use strict';
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {},
};
});
Open index.html in the browser, the output will be "This is myDirective" in heading1.
jqLite provides only the following jQuery methods:
In the case of angular jqLite, angular.element is used as a alias for jQuery or $ as in the jQuery. Let's take a look at some of the functions jqLite supports, replace the code corresponding to the function with app.js.
text()
'use strict';
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {
element.text('this is the myDirective directive');
},
};
});
prepend(), append()
'use strict';
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {
element.prepend('this is prepend text <hr/>');
element.append('<hr/> this is append text');
}
};
});
bind(), addClass(), toggleClass()
'use strict';
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {
element.addClass('btn btn-primary');
element.bind('click', function(event) {
element.toggleClass('btn btn-primary');
});
}
};
});
Similarly, all the other functions can be used like this. Also, if you want you can use complete jQuery library and use it with Angular. Angular & jQuery works well with each other.