Angular JS is a popular JavaScript framework used for building dynamic web applications. In this tutorial, we will be focusing on how to log data using promises and local storage in Angular JS.
Step 1: Set up AngularJS project
Before we start logging data with Angular JS, make sure you have Angular JS installed in your project. If not, you can include Angular JS in your project by adding the following code in your HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
Step 2: Create a controller
Next, we need to create a controller in our Angular JS project to handle the logging of data. Here’s an example of a simple controller that logs data using promises and local storage:
var app = angular.module('myApp', []);
app.controller('myController', function($scope, $q) {
var data = {
name: 'John Doe',
age: 30
};
var logData = function(data) {
var deferred = $q.defer();
// Log data with promises
// Simulate an API call here
setTimeout(function() {
console.log('Data logged:', data);
deferred.resolve();
}, 1000);
return deferred.promise;
};
logData(data).then(function() {
// Save data to local storage
localStorage.setItem('userData', JSON.stringify(data));
console.log('Data saved to local storage:', data);
});
});
In the code above, we have defined a controller called myController
that logs the data object using promises and saves it to local storage.
Step 3: Set up HTML
Now, we need to set up our HTML file to include the Angular JS app and controller. Here’s an example of how this can be done:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Angular JS Logging Data</title>
</head>
<body>
<div ng-controller="myController">
<h1>Logging Data with Angular JS</h1>
<p>Data:</p>
<pre>{{data | json}}</pre>
</div>
</body>
</html>
In the code above, we have defined an Angular JS app called myApp
and attached the myController
controller to the div
element.
Step 4: Run the project
Finally, you can run the project in your browser and check the console for the logged data and local storage for the saved data.
That’s it! You have successfully logged data with promises and saved it to local storage using Angular JS. You can now use this knowledge to build more complex applications with Angular JS.