Service in Angular that is created on each page transition or request

Currently learning the ropes of AngularJS (1.5) and endeavoring to create a feature that will allow me to modify certain elements in my layout based on the route.

My understanding is that I need a service for this purpose. This is the setup I currently have:

'use strict';

/* App Module */

var app = angular.module('app', [
  'ngRoute',
  'appControllers',
  'AppServices'
]);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {
    template: '<h1>Home page</h1>',
    controller: 'MainController'
  }).when('/page', {
    template: '<h1>Page</h1>',
    controller: 'PagesController'
  }).otherwise({
    redirectTo: '/'
  });
}]);
var appControllers = angular.module('appControllers', []);

appControllers.controller('MainController', ['$rootScope', 'AppSetup', function($scope, AppSetup) {
  $scope.app = AppSetup.build();
  console.log('home');
}]);

appControllers.controller('PagesController', ['$rootScope', 'AppSetup', function($scope, AppSetup) {
  AppSetup.setProperties({
    meta: {
      title: 'My Second Page'
    }
  });
  console.log('page');
  $scope.app = AppSetup.build();
}]);

var AppServices = angular.module('AppServices', []);

AppServices.service('AppSetup', [function() {
  var properties = {
      meta: {
        title: 'My App &bull; Best of the best'
      }
    },
    styles;
  this.setProperties = function(input) {
    this.properties = angular.extend(properties, input);
  };
  //TODO: This will override app-wide styles.
  this.setStyles = function(input) {
    this.styles = angular.extend({}, input);

  };
  this.build = function() {
    return {
      properties: properties,
      styles: styles
    };
  };
}]);

Check out Plunkr here

Currently struggling with how to reset the default value of the properties object when navigating back to the home page. It seems like it's set once on page load and then remains unchanged until altered manually. What would be the most effective approach to overcome this challenge?

I attempted following @Raul A.'s suggestion by adding a listener to the route, but unfortunately, it did not yield the desired results. The console output reflects this issue.

https://i.sstatic.net/kTZ6W.png

View the updated Plunkr here

Answer №1

If you are implementing routing and need to make changes, consider utilizing the $routeChangeSuccess event:

$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
   //Implement your desired changes here 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

What's the best way to set up multiple NestJS providers using information from a JSON file?

Recently diving into NestJS, I am in the process of building an application following the MVC architecture with multiple modules including: Project | +-- App.Controller +-- App.Service +-- App.Module | +-- SubModule1 | | | +-- SubModule1.C ...

What strategies can be utilized to enhance the cleanliness of these functions?

Is there a way to avoid adding new lines of JS code every time I add a new image to the HTML? $(document).ready(function() { $('.btn').click(function() { var bid = $(this).attr('id'); if(bid=="img1" || bid == "img2" || bid == "img3"){ ...

Send data between components using Angular directives

I have created a directive for a simple button App.directive('questionbutton', function(){ return { restrict: 'E', templateUrl: 'views/question-button.html' }; }); Another directive I have implemented ...

Discover the best locations within the city using Google's API to search by category

Users will choose a city and a type of place. The desired output is a Google Map showing all places in that city with the selected category. I'm looking to achieve this using Google Maps APIs. So far, I've tried using the Places API but it onl ...

The Ionic framework lacks support for the firebase and auth properties found in Firebase

Currently, I am developing a user-generated content feature along with buttons using ionic 5 and integrating it with the firebase app. I have been studying posts to incorporate them into my application. I am utilizing: "firebase": "^8.1.1&q ...

React - Unable to access variables that are not defined (trying to access 'params')

Someone else had a similar question regarding this tutorial, but unfortunately I am struggling with this more advanced section. An error occurred: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'params') at fetc ...

How does combineReducers in Redux determine which specific portion of the application state to send to the reducer?

While going through the Redux basics tutorial, I found myself a bit confused about how the code snippet below determines which part of the application state should be passed to each reducer mentioned in the combineReducers function. Does it simply rely o ...

Creating independent Javascript applications and HTML5 canvas games, optimized for V8 or tailored to the specific browser for optimal performance

Instead of solely targeting Chrome users due to browser performance issues, I am exploring alternative options to create an executable version of a canvas game. Is there a way to integrate v8 for non-Chrome users? Perhaps a web "wrapper" similar to Flash&a ...

Disabling the Enter key to submit an AJAX form is causing the focus to not move to the next input field

I've encountered a small issue that I can't seem to find a solution for (maybe my keyword search wasn't effective): The scenario: I have successfully prevented a form from being submitted when hitting the Enter key (13). It's importan ...

Determine if an object hierarchy possesses a specified attribute

When passing a set of options as an object like this: var options={ sortRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], filterRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], etc ...

Is there a method `Object.values()` available in TypeScript?

How can I iterate through all values of an Object in TypeScript that I want to use for filtering another array? I have searched on Google and came across Object.values(), but it seems like it doesn't work in TypeScript. Is there an equivalent method ...

The ng-view component in Angular seems to be causing issues with the routing functionality

I'm having trouble getting this to function properly. I've included the relevant code snippet, let me know if you need more details. Index.html <div class="col-md-3"><a href="#/liberals">Liberals</a></div> app.js var ...

TypeScript is not compatible with the intended ECMAScript version

Out of the blue, it seems like my VS17 has started transpiling my TypeScript to ECMAScript 6, but now VS is not accepting it and throwing a bunch of SCRIPT1002 and SCRIPT1006 errors suddenly: "JavaScript critical error at line 3, column 5 in http://localho ...

How to show a div for small screens only using Bootstrap 4 beta?

Previously, in Bootstrap alpha 6 I was able to achieve this by writing the following code for displaying a div's contents only for sm: <div class="hidden-md-up hidden-xs-down"> This content would only be visible for sm in Bootstrap 4 alpha 6 ...

Encountering an error when attempting to upload a file to S3 using JS Vue

I'm attempting to upload a file to my S3 bucket using the aws-s3 library, but I am encountering this error in the console: https://i.stack.imgur.com/lk47U.png Here is the code for the component: <template> <input type="file" @ch ...

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

Step by step guide on integrating a Slider into the header bullet point

I have successfully added the Bootstrap 5 website slider and it is working well. However, I am wondering how to position the slider at the top right with bullet points and without the back and previous arrows. Does anyone know the correct way to achieve th ...

The component I created is not visible on the index page

I am new to Angular and I am trying to create a simple component, but I am facing an issue where my component is not showing up on the index page. Can someone please help me with this? Here is my component named "List.Component.ts": import { Component } ...

The multiplayer game is experiencing significant delays due to issues with the websocket server

While developing a multiplayer game, I have implemented a WebSocket Server to facilitate communication between clients. However, I am experiencing sporadic delays in message delivery from the server to the client. These delays can be significant, sometimes ...