Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the issue (it only resulted in an error with the $http.post()). What might I be overlooking here?

app.controller('RegisterController', ['$scope','$http', function($scope,$http) {  
    $scope.user = {
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d0d5dcd8dff1d3ddd0d99fd2dedc">[email protected]</a>',
        password1: '1qaz2wsx',
        password2:'1qaz2wsx',
        password:'1qaz2wsx',
        username:'Admin',
        profile_picture:'',
        dobDay:'12',
        dobMonth:'12',
        dobYear:'1993',
        date_of_birth:'',
        stateMessage:'',
        messageColor:'white',
    };
    
    var transfer = function(){
        $http.post('http://localhost/cw/index.php/rest/resource/user/action/create',$scope.user).then(function successCallback(response) {
            if(response.data.status!=null){
                if(response.data.status=='success'){
                    $scope.user.stateMessage = 'success';
                    $scope.user.messageColor = "green";
                }
                else if(response.data.status=='failure'){
                    $scope.user.stateMessage = response.data.message;
                    $scope.user.messageColor = "red";
                }
                
            }
        },function errorCallback(response) {
            $scope.user.stateMessage = "Error occured.";
            $scope.user.messageColor = "red";
        });
        
    };
    
    $scope.submit = function(){
        $scope.user.stateMessage="";
        $scope.user.messageColor="white";
        var proceed = true;
        
        if(!validateFields()){
            $scope.user.stateMessage = "All fields must be filled!";
            $scope.user.messageColor = "red";
            proceed = false;
        }
        
        if(validateDate($scope.user.dobDay,$scope.user.dobMonth,$scope.user.dobYear)){
            $scope.user.date_of_birth= $scope.user.dobYear+"-"+$scope.user.dobMonth+"-"+$scope.user.dobDay;
        }else {
            proceed = false;
            $scope.user.stateMessage = "Date is invalid!";
            $scope.user.messageColor = "red";
        }
            
        if($scope.user.password1!=$scope.user.password2){
            proceed = false;
            $scope.user.stateMessage = "Passwords don't match!";
            $scope.user.messageColor = "red";
            
        }else $scope.user.password = $scope.user.password1;
        if(proceed){
            var file = document.getElementById('filePicker').files[0];
            reader = new FileReader();

            reader.onloadend = function(e) {
                $scope.user.profile_picture = JSON.stringify(e.target.result);
                $scope.$apply();
                console.log($scope.user.profile_picture);
                transfer();
            }
            reader.readAsDataURL(file);
        } 
        
        function validateFields(){
            /*some form validation*/
            return true;
        }
        
        function validateDate(day,month,year){
          /*some date validation*/
            return true;
        }
       
    }
}]);

HTML code

 <div ng-controller="RegisterController">
        <span style="background-color:{{user.messageColor}}"><h4>{{user.stateMessage}}</h4></span>
    </div>
<table style="text-align: left" ng-controller="RegisterController">
                            <tr>
                                <td>
                                    Username
                                </td>
                                <td>
                                    <input type="text" ng-bind="user.username" ng-model="user.username">
                                </td>       <td>&nbsp;</td><td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td>
                                    Email
                                </td>
                                <td>
                                    <input type="email" ng-bind="user.email" ng-model="user.email">
                                </td>       <td>&nbsp;</td><td>&nbsp;</td>
                           </tr>
                           <tr>
                                <td>
                                    Password
                                </td>
                                <td>
                                    <input type="password" ng-bind="user.password1" ng-model="user.password1">
                                </td>       <td>&nbsp;</td><td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td>
                                    Retype password
                                </td>
                                <td>
                                    <input type="password" ng-bind="user.password2" ng-model="user.password2">
                                </td>       <td>&nbsp;</td><td>&nbsp;</td>    
                           </tr>
                           <tr>
                                <td>
                                    Date of Birth
                                </td>
                                <td>
                                    <input type="text" ng-bind="user.dobDay" ng-model="user.dobDay" value="DD" size="2" maxlength="2">
                                    <input type="text" ng-bind="user.dobMonth" ng-model="user.dobMonth" value="MM" size="2" maxlength="2">
                                    <input type="text" ng-bind="user.dobYear" ng-model="user.dobYear" value="YYYY" size="4" maxlength="4">
                                </td>    
                           </tr>
                           <tr>
                                <td>
                                    Profile picture
                                </td>
                                <td>
                                    <input id="filePicker" type="file" ng-bind="user.profile_picture" ng-model="user.profile_picture" accept="image/*">
                                    
                                </td>    
                           </tr>
                           <tr>
                               <td></td>
                               <td style="float:left">
                                    <button ng-click="submit()">Submit</button>
                               </td>
                           </tr>
                        </table>

Answer №1

It appears that using the same controller in multiple instances is causing issues for me. I found success by relocating the status div into the table assigned to the controller. While there are methods to share data between controllers using a service, I am choosing not to explore this option as it is solely for coursework purposes.

AngularJS: Sharing Data of a Single Controller Across Two Separate Areas on the Page

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

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

Concealing alert messages automatically in CodeIgniter PHP after a certain amount of time

After attempting to use a script to hide the flash message once displayed, I found that it was not working as expected. The flash message remains visible until the page is refreshed. Controller: if ($this->email->send()) { $this- ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

JQuery addClass function not functioning properly when used in conjunction with an AJAX request

I have a website where I've implemented an AJAX pagination system. Additionally, I've included a JQUERY call to add a class to certain list items within my document ready function. $(document).ready(function(){ $(".products ul li:nth-child(3 ...

Tips for validating forms within a modal that includes tabs using angularJs

I have a modal form in angular with uib-tabset that includes tabs for forms A, B, and C within the footer section of the modal. However, I am facing an issue where I cannot access the forms to enable/disable the save button on the footer. The forms appear ...

Tips for Utilizing jQuery each Loop

I am attempting to create a foreach loop that will iterate through hidden values on the page, compare them with an external API using Ajax, and display the API results in a < ul > for example. Sample model ITEM1 metavalue (which needs to be che ...

What causes an infinite loop in my app when passing a prop, and why doesn't it update the prop as expected?

Trying to pass a single variable from one component to another should be simple, but it's turning out to be more complicated than expected. I have a Search bar in one component and I want the input from that search bar to display in another component. ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

AngularJS: Iterating through all isolated scope directive templates and performing a click event on one of them

Here is the HTML code I am working with: <div ng-repeat="mydata in data" class="ng-scope ng-binding"> <p class="ng-binding">{{mydata.postdata}}</p> <div my-rating rating-value="rating" data-cat="post" data-id="mydata.id" >& ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

Troubleshooting not locating view files in ExpressJS and implementing client-side JavaScript and CSS deployment in ExpressJS

My JavaScript file is located in the same directory as my HTML file, and I am trying to render it. I'm unsure of what I may be missing. How difficult could it possibly be? var express = require('express'); var app = express(); app.engine( ...

Calculate the overall length of a specified time interval using Node Js

My task involves calculating overtime based on work start and end times. We are looking to calculate overtime hours that fall outside of the regular work schedule. For example, the regular work timings are from 10:00 AM to 07:00 PM Overtime needs to be ...

Struggling to align nested grids in the center

I'm currently following a mobile-first approach in designing my website. The entire website is contained within one main grid, and I also want to include smaller grids that will serve as links to other HTML pages. I created a sample nested grid but am ...

Tips to minimize a responsive Bootstrap 4 menu by clicking elsewhere

When using my bootstrap nav menu on desktop, it closes when clicking outside of it. However, this feature doesn't work on mobile devices. I attempted to modify some code from a codepen to match the classes on my website, but it didn't work. Bel ...

Whenever my code is used within Google Sites, it triggers the opening of a new and empty tab

When using this code inside an HTML box in Google Sites, a problem arises. It seems to work perfectly fine in Internet Explorer and Chrome when saved to an HTML file. However, within Google Sites, it unexpectedly opens a new tab with no data. The code st ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

Problem encountered with imaskJS in handling the formatting of data with forward slashes

After conducting tests on the frontend of the imask website at , it has been verified that utilizing a forward slash for date formatting results in the exclusion of the final digit of the date. Various attempts were made, including: IMask( field, ...

"Learn the process of setting a variable in ng-model within an input field based on a specific condition

I need to dynamically assign an ng-model variable based on a condition. For instance: <input type="text" ng-model="item.model[multilang]" > The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "E ...