Satyadev Satyadev - 1 month ago 6
Javascript Question

How to run the service on page load

I have the function inside service in angular module but how do I run the service on page load. I am not using any controller here

Code:

var app = angular.module("myTmoApppdl", [])
.service('populatePageObjsService', function () {

var self = this;

//digitalData is a global object
self.populatePage = function (digitalData) {
var dataPageObject = document.getElementById('metaJson').getAttribute("data-pageObject");
var jsonPageObject = JSON.parse(dataPageObject);

for (var key in jsonPageObject.page.pageInfo) {
var value = jsonPageObject.page.pageInfo[key];
if (digitalData.page.pageInfo.hasOwnProperty(key)) {
digitalData.page.pageInfo[key] = value;
}
}
console.log("Page data populated successfully: ", digitalData.page.pageInfo);
}();
});


I tried using the
()
after function but it didn't execute the function

Update:

var app = angular.module("myTmoApppdl", []).run(function () {
app.service('populatePageObjsService', function () {
var self = this;
self.populatePage = function (digitalData) {
var dataPageObject = document.getElementById('metaJson').getAttribute("data-pageObject");
var jsonPageObject = JSON.parse(dataPageObject);

for (var key in jsonPageObject.page.pageInfo) {
var value = jsonPageObject.page.pageInfo[key];
if (digitalData.page.pageInfo.hasOwnProperty(key)) {
digitalData.page.pageInfo[key] = value;
}
}
console.log("Page data populated successfully: ", digitalData.page.pageInfo);
};
});
});

Answer

You can call your service method in .run() block

var app = angular.module("myTmoApppdl", []);   
app.run(function(populatePageObjsService){ // inject your service here
   //use your service here
});
app.service('populatePageObjsService', function() {
     // your service code here
});
Comments