Is it possible to modify variables in the controller when the route is changed?

My application utilizes a template and several views that are dynamically rendered based on their route:

popApp.controller('HomeCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {    
  $scope.showNow = true;
}]);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/signup', {
      controller:'HomeCtrl',
      templateUrl:'partials/newAccountStage.html'
    })
    .when('/', {
      controller:'HomeCtrl',
      templateUrl:'partials/home.html'
    });
}]);

Within my template, I have elements that are meant to be displayed most of the time but hidden when certain routes are accessed:

<div ng-show="showNow"></div>

Specifically, when the user navigates to the /signup route, I want to hide certain elements.

What is the most angular-friendly approach to achieve this functionality?

Answer №1

One common practice in development is to separate controllers for different views. One way to achieve this is by using the $routeProvider as demonstrated below.

popApp.controller('HomeCtrl', [
    '$scope', 
    '$routeParams', 
    '$http', 
    function($scope, $routeParams, $http) {    
        $scope.showNow = true;
    }
]);

popApp.controller('SignupCtrl', [
    '$scope', 
    '$routeParams', 
    '$http', 
    function($scope, $routeParams, $http) {    
        $scope.showNow = true;
    }
]);

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/signup', {
      controller:'SignupCtrl',
      templateUrl:'partials/newAccountStage.html'
    })
    .when('/', {
      controller:'HomeCtrl',
      templateUrl:'partials/home.html'
    });
}]);

Another approach is to utilize the $stateProvider when dealing with signup functionality within another controller to alter the page's "state." In this scenario, SignupCtrl could be a state of HomeCtrl where you set the state to 'not signed up' and utilize the SignupCtrl.

Here's more information on $stateProvider.

Below is an example of how this syntax might be implemented:

$stateProvider.state('not signed up', {
  template: 'partials/newAccountStage.html',
  controller: SignupCtrl
})

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

I am experiencing an issue wherein after using jquery's hover() function, the CSS :hover state is not

Following the jquery hover function, the css hover feature ceases to work. In my html, there are multiple svg elements. A jquery script is applied where hovering over a button at the bottom triggers all svg elements to change color to yellow (#b8aa85). S ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...

Convert Python strings into HTML JavaScript blocks using Jinja2

Having trouble passing a string to an HTML page in the "<script>" block. I am currently using Python, Flask, and Jinja2. Python code: def foo(): return myString #"[{title: 'Treino 7-Corrida',start: '2015-12-08',color: '#d ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Leveraging scanner-js within an Angular2 environment

Exploring ways to incorporate Scanner-JS into my Angular2 project, a tool I discovered while tinkering with the framework. Being a novice in Angular2, this question might be elementary for some. I successfully installed scanner-js via npm npm install sc ...

Is there a way to verify if a FormData file has no content?

Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg. <label>Color: <input type="color" name="bgColor" value="#0000 ...

Finding the chosen selection in AngularJs

I've been working on this script for hours and I'm struggling to output the text instead of the value of a select option in AngularJS in HTML through data binding. Despite my efforts, I keep getting the value instead of the text. How can I resolv ...

What are the reasons for avoiding placing CSS code directly within HTML?

Situation: My website is dynamically served, with all CSS and javascript directly embedded into the HTML document to optimize speed. Advantages: Reduces web requests Fewer files downloaded Speeds up webpage loading time Disadvantages: Potential cachin ...

Stopping a velocity.js animation once it has completed: is it possible?

For the pulsating effect I'm creating using velocity.js as a fallback for IE9, refer to box2 for CSS animation. If the mouse leaves the box before the animation is complete (wait until pulse expands and then move out), the pulsating element remains vi ...

Guide on inserting a new column into an array of objects in Vue

Below is the fetch method I have defined to retrieve recordings from the database. However, I need assistance in adding a new column to each record specifically for frontend purposes. Can someone help me with this problem? <script> export default { ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

Pressing a key will initiate a time delay before

I have a coding challenge where I need to navigate through a sprite sheet using setTimeouts. Everything is functioning as expected, but I am curious about implementing a feature that allows me to skip frames by pressing the "m" key. Essentially, I want it ...

Retrieving information from a separate JavaScript file

I'm currently developing a Discord Bot and my code is all contained within one file. My goal now is to break this code up into multiple files for better organization. For instance, I plan to have: index.js which will handle all the requires (e.g. var ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

What could be causing the issue with Collection.find() not functioning correctly on my Meteor client?

Despite ensuring the correct creation of my collection, publishing the data, subscribing to the right publication, and verifying that the data was appearing in the Mongo Shell, I encountered an issue where the following line of code failed to return any re ...

What is the best way to limit a plugin to only one version of jQuery when there are 2 versions included on a page?

As I develop a piece of Javascript code to embed into my client's websites, I have concerns about potential conflicts with other versions of jQuery that they may be using. While I have found some guidance in the jQuery documentation, implementing it l ...

Unable to retrieve JSON element using Fetch

I'm attempting to retrieve a JSON file and exhibit its components within a div. Here is the JSON data I have: [ { "0":{ "host_id":"129230780", "host_names":"STK Homes", ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...