Losing value in Angular service when the view is changed

I am currently working on a project to create a basic Angular application that retrieves data from Instagram. The concept involves the user inputting a hashtag on the main page, which then redirects them to another page where posts related to that hashtag are displayed.

My challenge has been passing the hashtag as a variable through a service. However, I've noticed that when the view is changed, the value of the variable gets overwritten. Even though I can confirm the value being set initially, it somehow gets lost when the page transitions.

Below is the structure of my service:

var instagramApp = angular.module('instagramApp')
.factory('feedData', function($rootScope) {
    var config = {};
    return {
        setHashtag: function (x) {
                config.hashtag = x;
        },
        getHashtag: function () {
            return config.hashtag;
        }
    }
});

Furthermore, here are the two controllers in use:

The controller for setting the hashtag (/index.html):

instagramApp.controller('indexController', ['$scope', 'feedData', '$window',
function($scope, feedData, $window){

$scope.generate = function(){
    feedData.setHashtag('marcheet');
    console.log(feedData.getHashtag());
    $window.location.href = '/results.html';
};

}]);

The controller responsible for retrieving the hashtag (/results.html):

instagramApp.controller('instagramController', ['$scope', 'Instagram', '$http', 'feedData',
function($scope, Instagram, $http, feedData){

    feedUrl = '/feed/?hashtag=' + feedData.getHashtag() +'&count=20';
    console.log(feedUrl);
    createStoryJS({
      type:       'timeline',
      width:      '800',
      height:     '600',
      source:     feedUrl,
      embed_id:   'my-timeline'
    });
}
]);

Answer №1

According to @pcguru, the browser reloads your angular app when you execute the line

$window.location.href = '/results.html';
.

Angular monitors changes in the URL when users click on links or use $location.path('/someurl'); (an angular service for managing URL information). Your javascript code bypasses this functionality.

Refer to the Angular documentation on $location

What doesn't it [$location] do?

It does not trigger a full page refresh when the browser URL is modified. To refresh the page after changing the URL, utilize the lower-level API, $window.location.href.

If you want to change the URL programmatically, use $location.path(url). For navigating within the app without reloading the page, set up routing using angular-route.js (https://code.angularjs.org/1.3.15/angular-route.js) and inject $routeProvider into your app's config method

(function() {
    'use strict';

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

    app.config(configFunc);

    function configFunc($routeProvider) {
         $routeProvider.when('/', {
             templateUrl: 'path/to/your/template.html',
             controller: 'HomeController'
         })
         .when('/results', {
             templateUrl: 'path/to/your/template.html',
             controller: 'ResultsController'
         });
    }
}());

Answer №2

To manage the location change efficiently, it is important to utilize Angular's router. This helps in avoiding a complete reload of the application every time you navigate to a details view.

For more information on Angular's route handling, you can refer to this documentation.

Answer №3

As mentioned by @pcguru, the use of angular Router OR ui-router is essential to maintain the context of your single Angular Page.

The AngularRouter is an integral part of the Angular framework and is straightforward to implement. On the other hand, Ui-Router serves as a complement, offering greater customization options and the ability to utilize multiple views simultaneously. For beginners in Angular, adding this extra complexity may not be necessary.

Redirecting a page using

$window.location.href = '/results.html';
will result in a page reload, which is not the recommended way to handle navigation in Angular.

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

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

The ng-app feature is causing the script to run endlessly

Currently, I am troubleshooting an issue within my angular application that is built on the asp.net web application empty template. The problem arises when I utilize ng-app; if I leave it blank, the $routeProvider fails to initialize. However, if I specify ...

Tips for incorporating an entire JavaScript file into a React JS project

I'm facing an issue with a .js file (JavaScript file) that lacks exports code, containing only a constructor and some prototype methods. I am trying to incorporate this file into my ReactJS App. My approach involved adding a script tag in client/inde ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Is it possible to incorporate a YouTube video into a webpage without displaying any external links to YouTube above the video player?

Looking for a solution to embed a YouTube video on my webpage without the link appearing when hovering over it and without the suggested videos at the end. Just the option to replay the video without the distraction of related videos. ...

Is there a way to guide users to their designated page on Node.js?

My goal is to seamlessly redirect users to their designated pages based on their role. If the user is a regular user, they should be redirected to the user menu. On the other hand, if it's an employee, they should be directed to the employee menu. E ...

Arrange images with haphazard placement

Can someone guide me on creating a block of images when working with an array of random items? https://i.sstatic.net/qEcQy.png ...

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

ng-select will solely output the term 'collection'

i am having an issue with a ng-select in my contact form. everything is being received correctly except for the value of the ng-select. Instead of getting the selected option from the ng-select, the system just returns the word "array". Below is the port ...

I can't seem to figure out which of these 4 statements is free of syntax errors

Can you identify which code block does not contain a syntax error? Out of the 4 options below, one of them is free from any syntax mistakes. alert("hello "+3+" times); alert("hello "+3 times); alert("hello +3+ times"); alert("hel ...

Is it possible to modify the contents within the JSP div tag without replacing them through an AJAX call?

In my JSP, I face a scenario where there is a div tag with scriptlet content that pulls data from the database every time a request is received from the server. Previously, I was refreshing the entire page with each update, which not only loaded all the re ...

Accessing a global variable within a jQuery .each function

I'm struggling to modify the global variable within an each function var total_ctc_change = 0; $('.table' + employeeid + ' thead th').each(function(index, value){ total_ctc_change++; }); ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Substitute the value in the object associated with a mystery key with a different value from the second object

I am dealing with the following objects: http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 } input= {"phone": "2", "id": "258 }, Can someone help me find the #phone# val ...