<!DOCTYPE html>
<
html
lang
=
"en"
ng-app
=
"myApp"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content="
width
=
device
-width,
initial-scale
=
1
.0">
<
title
>
Angular $rootScope Example -
Advanced with Service
</
title
>
<
style
>
body {
font-family: 'Arial', sans-serif;
text-align: center;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
h1 {
color: #4CAF50;
}
h3 {
color: #333;
}
input {
padding: 8px;
margin: 10px;
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin: 5px;
}
.highlight {
transition: background-color 0.5s;
}
.highlight:hover {
background-color: #45a049;
}
.item-list {
list-style: none;
padding: 0;
}
.item {
background-color: #fff;
padding: 10px;
margin: 5px;
border-radius: 5px;
display: inline-block;
}
</
style
>
</
head
>
<
body
ng-controller
=
"myController"
>
<
h1
>GeeksforGeeks</
h1
>
<
h3
>Approach 2: Using Angular $rootScope with Service</
h3
>
<
input
type
=
"text"
ng-model
=
"newItem"
p
laceholder
=
"Enter a new item"
>
<
button
ng-click
=
"addItem()"
class
=
"highlight"
>
Add Item
</
button
>
<
button
ng-click
=
"clearItems()"
class
=
"highlight"
>
Clear Items
</
button
>
<
ul
class
=
"item-list"
>
<
li
ng-repeat
=
"item in rootScopeService.getItems()"
class
=
"item"
>
{{ item }}
<
button
ng-click
=
"removeItem(item)"
class
=
"highlight"
>
Remove
</
button
>
</
li
>
</
ul
>
<
script
src
=
</
script
>
<
script
>
angular.module('myApp', [])
.service('rootScopeItemService', function ($rootScope) {
this.getItems = function () {
return $rootScope.rootScopeItems || [];
};
this.addItem = function (item) {
$rootScope.rootScopeItems =
$rootScope.rootScopeItems || [];
$rootScope.rootScopeItems.push(item);
};
this.removeItem = function (item) {
const index =
$rootScope.rootScopeItems.indexOf(item);
if (index !== -1) {
$rootScope.rootScopeItems.splice(index, 1);
}
};
this.clearItems = function () {
$rootScope.rootScopeItems = [];
};
})
.controller('myController',
function ($scope, rootScopeItemService) {
$scope.addItem = function () {
rootScopeItemService.addItem($scope.newItem);
$scope.newItem = '';
};
$scope.removeItem = function (item) {
rootScopeItemService.removeItem(item);
};
$scope.clearItems = function () {
rootScopeItemService.clearItems();
};
$scope.rootScopeService = rootScopeItemService;
});
</
script
>
</
body
>
</
html
>