AngularJS constant Recipe

Hello Friends

In this article, we will learn How to create and use AngularJS constant Recipe ?

constant recipe creates JavaScript Object returns same JavaScript Object, Which is created only once. We can access it any where with in the application including config block. Since it is created only once in the lifetime of an Angular application. therefore it is also singleton.

We can create constant recipe as follows.

var ng = angular.module("myApp", []); ng.constant("ConstantModel", { "PI":3.14, });

Injecting constant recipe in config block.

ng.config(function (ConstantModel) { console.log(ConstantModel); })

Injecting constant recipe in controller.

ng.controller("MyController", ['$scope', 'ConstantModel', function ($scope, ConstantModel) { $scope.PI = ConstantModel.PI; }]);

Copy following code to understand constant recipe.

<!DOCTYPE html> <html> <head>     <meta charset="utf-8" />     <title></title>     <link href="bootstrap-4.2.1/css/bootstrap.min.css" rel="stylesheet" />     <script src="jquery-3.3.1/jquery-3.3.1.min.js"></script>     <script src="bootstrap-4.2.1/js/bootstrap.bundle.min.js"></script>     <script src="angular-1.7.8/angular.min.js"></script> </head> <body>     <div class="container" ng-app="myApp" ng-controller="MyController" ng-cloak>         <nav class="navbar navbar-expand-lg navbar-light bg-light">             <a class="navbar-brand" href="#">&nbsp;</a>         </nav>         <div class="row">             <div class="col-md-6">                 <div class="form-group">                     <label class="control-label">PI</label>                     {{PI}}                 </div>             </div>         </div>     </div>     <script>         var ng = angular.module("myApp", []);         ng.constant("ConstantModel", {             "PI":3.14,         });         ng.config(function (ConstantModel) {             console.log(ConstantModel);         })         ng.controller("MyController", ['$scope', 'ConstantModel', function ($scope, ConstantModel) {             $scope.PI = ConstantModel.PI;         }]);     </script> </body> </html>

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories