Executing AngularJS controller upon view initialization

I am working on an angularJS single page application that loads views per click.

My login and Index are combined in one HTML file. I have managed it using ng-show and ng-if directives.

The process is as follows: Index.html and IndexController.js: The login page has a ng-show="!isLogin" condition, and if the user is authenticated, isLogin will be set to true.

https://i.sstatic.net/nFFd4.jpg

This allows me to access my home page. The code looks like this:

<section id="content">
  <div ng-view>
  </div>
</section>

Next, there is a default.html which contains the initial page to be displayed after 'isLogin' becomes true, with the DashboardController.js as its controller.

https://i.sstatic.net/aTPiR.jpg

However, the controller does not run automatically unless I click the button on the navigation bar.

https://i.sstatic.net/4oBbj.jpg

For example, the "Overdue Bills" section does not load until I click on "Dashboard" in the NavBar.

So, how can I make my controller run right after logging in? Any assistance would be greatly appreciated.

This project is for educational purposes.

Thank you.

EDIT: DashboardController.js

(Controller code goes here)

Index.html

(HTML code goes here)

EDIT2: for NTP

(Additional functionality code snippet goes here)

Answer №1

Controllers are essential in AngularJS, as they are bound to views either through the router or ng-controller directive. When a view is rendered in the DOM, its associated controller is invoked.

<div ng-controller="DashboardController" >
</div>

If you are using ngRoute, make sure to specify the controller in your default.html file or within your router configuration. This way, when you navigate to the dashboard after logging in, the controller will be triggered.

Avoid using

ng-if="isLogin" 

This can result in a blank page for non-logged-in users. Instead, create a shared service for managing login status and check it in your controller. If the user is not logged in, redirect them back to the login page.

Answer №2

If the ngIf directive is used, the dashboard section will be recreated when isLogin is true. Therefore, your dashboard controller will run only when isLogin is true.

  <div id="dashboard" ng-if="isLogin" ng-controller="DashboardController">
  </div>

Check out the demo 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

Creating Vue Components in PHP with no need for Webpack or Bundlers

Our company is currently in the process of incorporating Vue into our workflow, but we are facing challenges due to the lack of Javascript Build tools like Webpack. This means we cannot use Babel or Template Literals (`), making it difficult to define Comp ...

Guide on validating React input fields using custom validation methods

Currently, I am working with React and dynamically creating new input fields while utilizing React-hook-form for validation purposes. My approach involves: Having a dropdown with numbers as options, such as 1, 2, 3, 4 Generating input fields based on the ...

Why would you need multiple root handlers?

One interesting feature to note is that multiple callback functions can be used as middleware to handle a request. These callbacks can take on different forms - they could be in the form of a single function, an array of functions, or even a combination of ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...

utilizing formArray of formGroup for mat-select within an angular application

I am currently working on a project where I require a material select box that allows for multiple values to be selected. These values are retrieved from an API that returns an array of objects. My goal is to generate a formarray of formgroups whenever a u ...

Using Angular to create dynamic HTML templates

How can I integrate an HTML template instead of Jade in my Angular application? layout.html: <body> {% block content %}{% endblock %} <h1>Hello!! What's up from layout</h1> </body> index.html: {% extends 'includes/layo ...

The element div is not permitted as a child of the element h5 in this particular scenario

My code snippet is as follows: $compile .= "<h5 data-count='".$acctemmpi. "' class='shortcode_accordion_item_title expanded_". $expanded_state . "'>" . $title . "<div class='ico'&g ...

Is it possible for an animation to complete even if it is stopped midway?

I am currently working on a media player project where I have implemented a scrolling marquee effect for the song meta information using JavaScript and CSS. The scrolling effect only occurs when the track is playing, and I achieve this by adding/removing ...

The useRouter hook from next/router was unable to connect because NextRouter was not activated

import { useRouter } from 'next/router'; const Navbar2 = () => { const router = useRouter(); return ( <nav className={`fixed top-0 w-full px-10 bg-white p-4 transition-all duration-500 ${isVisible ? 'top-0' : 'top-[-1 ...

Passing a JavaScript variable to PHP within an HTML document: Parsing data from Wikipedia

I am currently working on passing a JavaScript variable named $url to a PHP function in the same HTML file. The idea is that a user inputs a species into a textbox, and the Wikipedia API is called to check if the input matches a Wikipedia page. If a match ...

Unable to modify the value of data using the data() method

Just a basic HTML code snippet <div class="this" data-info="false"></div> $('.this').data('info'); This will correctly output: false $('.this').data('info', 'true'); data-info remains u ...

Encountering Error 1 in Cordova File Transfer with Laravel Framework

I'm currently developing an Ionic angular 1 application where I need to upload an image to my laravel api server. However, I keep encountering error code 1 (File not found?) along with a laravel PHP error message as the response body. I've tried ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Is there a way to assign retrieved data to the $scope.variable?

I'm relatively new to both JavaScript and Angular. I have a piece of code that fetches data from an API and successfully prints it to the console, but I'm facing issues when trying to assign this data to $scope.saveData. It seems to only work wit ...

Understanding how to parse a JSON object in JavaScript is a

In my JSON object, I have the following data: rows = [{name:"testname1" , age:"25"}, {name:"testname2" , age:"26"}] My goal is to extract the names and store them in a variable like this: name = "testname1, testname2"; ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Aggregate and consolidate data based on multiple criteria while ensuring data integrity and maintaining type compliance

In search of a solution, I aim to organize an array of objects by a specified number of keys and calculate the sum of values of another set of keys. For instance, consider the following array: const arr = [ { type: "triangle", color: "green", available ...

Guide on triggering a C# method following a JavaScript function

After updating the Input Text field in a web forms application using a JavaScript method, the change method in the C# code does not seem to work. How can I resolve this issue? <asp:TextBox ID="Value1" Columns="2" MaxLength="3&qu ...

Utilizing Angular with Onsen UI for efficient AJAX requests

Currently, I am delving into the world of app development with Monaca. I have been working on tweaking a sample application that uses Onsen and Angular frameworks. My main goal is to retrieve data from a remote file located on my server whenever necessary ...