The AngularJS Controller is running before the template is fully loaded

Here is an example of my email verification link:

.when('/user/register/verify/:verify_code?', {
      controller: 'AngularRegisterVerifyPage',
      templateUrl: '/user/register/verify'
 })

This is how my input field is set up:

input(ng-model="formData.verify_code", name="verify_code", type='text', class='form-control', placeholder='Verification Code', id="verify_code")

The code below should execute when the template loads to insert the parameter into the text field:

 document.getElementById('verify_code').value = "Test"; // Debugging Test Code
 $scope.formSubmitted = false;
 if ($routeParams.hasOwnProperty("verify_code")) {
      document.getElementById('verify_code').value = $routeParams.verify_code;
 }

However, it seems like the controller runs this before the template actually loads because the input field is empty when the page loads. I am looking for guidance on how to properly achieve this functionality. I have tried researching solutions like "Load Template after Controller loads" without success. Thank you.

Edit:

I attempted adding ng-init="loadCode()" to the input field but it did not solve the issue.

 $scope.loadCode = function() {
      if ($routeParams.hasOwnProperty("verify_code")) {
           console.log('Called');
           document.getElementById('verify_code').value = $routeParams.verify_code;
           console.log($routeParams.verify_code);
           console.log(document.getElementById('verify_code').value);
      }
 }

Answer №1

Manipulating the DOM to change input values in AngularJS is not necessary. Angular provides various mechanisms to streamline development work.

To achieve this, you can simply modify your code like so:

.controller('AngularRegisterVerifyPage', function($scope, $routeParams){
     $scope.formData = {};
     if ($routeParams.hasOwnProperty("verify_code")) {
         //Updating the model value will automatically reflect in the view
         $scope.formData.verify_code = $routeParams.verify_code;
     }

});

For those new to Angular, here's a helpful resource: “Thinking in AngularJS” if I have a jQuery background?

Refer to the ngModel Documentation for more information.

Enjoy exploring AngularJS! :)

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

Listing of mongodb commands available post establishing connection

Is there a way to implement the method mentioned in this documentation? Check it out here Initially, I tried: const mongoose = require('mongoose') mongoose.Promise = global.Promise mongoose.connect(`mongodb://example.com/db`) const db = mongoo ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Searching for multiple array elements based on their values can be achieved by using various techniques

I am trying to find a way to select multiple elements from an array that share the same value. When I use array.find(), it only returns the first element that matches the condition. For example, in the code below, only "Donald Trump" is displayed in the co ...

The operation fails to yield a result

I have a seemingly simple question that has been stumping me for the past two days. I need to retrieve data from a server and wrote a basic function to do so. However, I am facing an issue with it. $scope.myTar = function() { return 5; }; $scope.iden ...

Bringing Vue Components Together in Laravel: A Guide to Component Importation

Recently, I started learning Vue.js and I am looking to understand how to use component. Unfortunately, when I attempted to import my component into another component, it didn't work as expected. The framework I am currently using is Laravel 5.8 and I ...

"Troubleshooting the issue of Delete Requests failing to persist in Node.js

Whenever I send a delete request to my node.js server, it can only delete one item from my JSON file until the server restarts. If I attempt to make a second delete request, it successfully deletes the item but also reverts the deletion of the last item. ...

Whenever a menu option is clicked in Umbraco, the page always redirects to the route #/content

After updating my site to the latest version available, I encountered a problem: Whenever I click on any link in the menu on the admin page (/umbraco) The temporary solution I discovered is Click on the link Go to profile Edit Confirm that you want to ...

What steps are involved in utilizing a custom filter within ng-pluralize based on the count parameter?

<ng-pluralize count="data.amount | customFilter" when="{1: 'one item', 'other': '{} items'}"> </ng-pluralize> Is it possible to apply a custom filter to the count property? The customFilter function should return ...

What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use ...

Rollup - incomplete packaging due to missing child component in repository

After working on my component library in vue and using rollup to wrap it up, I encountered an issue with the mixins not getting included in the final library. Initially, I suspected that the problem lied in the paths since most of the mixins were local. I ...

triggering the bootstrap datetimepicker's onChange event when selecting start and end dates

In my project, I have implemented a bootstrap datetimepicker for selecting start and end dates, along with switch buttons to quickly set dates for today, last week, and all time. Here is how it looks: https://i.sstatic.net/nE39s.png For the datetimepicke ...

The asynchronous functionality of Azure IoT Edge node SDK's invokeDeviceMethod seems to be malfunctioning

I am attempting to asynchronously return a result for a direct method call. This is what I attempted: const client = Client.fromConnectionString(process.env.AZ_IOT_CONNECTION_STRING); const methodParams = { methodName: "method", payload: 10, // Numbe ...

Tips for incorporating a JavaScript file directly into your HTML code

I'm working with a compact javascript file named alg-wSelect.js, containing just one line of code: jQuery('select.alg-wselect').wSelect(); This script is used by a wordpress plugin. My question is whether it's feasible to incorporate th ...

Explanation for the strange floating math in JavaScript - Understanding the IEEE 754 standard for laymen

When it comes to JavaScript and working with floating point numbers, I always feel a bit lost. Dealing with decimals makes me nervous because I'm never quite sure what's happening behind the scenes. If only I understood how the IEEE 754 standard ...

Leverage the selected values to dynamically generate a table using jQuery

Can someone help me figure out how to store multiple values from a selection and then create an array using jQuery? Here's the scenario: In my multiple selection, I have 5 values: <select name="animal" id="animal" multiple="multiple">    ...

Storing data for extended periods in NodeJS

Currently, I have a node server up and running. To maintain its uptime when I'm not actively developing, I utilize npm forever. However, for editing purposes (such as restarting the app upon edits or uploads), I rely on npm nodemon. After restarting ...

Having difficulty duplicating a button with a click event using jQuery

I have implemented a button that reveals a phone number when clicked using the code below: var shortNumber = $("#phone_ch").text().substring(0, $("#phone_ch").text().length - 12); var onClickInfo = "_gaq.push(['_trackEvent', 'EVENT-CATEGOR ...

Lazy loading of AngularJS modules allows for deferred loading of code

When working on my project, I decided to separate angular services into different files. Each file or service should be a part of a shared module called 'com.mysite.services'. For example: ServiceA.js ServiceB.js ServiceC.js But when definin ...

Issue involving retrieving keys from multiple classes in a JSON object

I am facing some difficulties with JSON and JavaScript as I am a beginner in this area. Currently, I am attempting to iterate through all the keys["name"] of this JSON data. var l = [{ "pages": [ { "name": "Scan", "elements": [ { "type": ...

Why is the response undefined when I resize an image twice using a JavaScript promise chain?

When I attempt to resize an image using the sharp library twice in my route handler, the result returned is undefined. Despite the resized images being displayed, it seems that calling image.resize and .toBuffer() multiple times is causing corruption in th ...