Challenges with Angular scoping

I am facing an issue with a form in my ng-controller where it doesn't seem to update the properties in the controller as expected. After some research, I realized my misunderstanding of prototypal inheritance. Thanks to information from the internet and SO, I made changes to my code. However, it is still not functioning correctly and I am unable to determine the reason.

Here is the HTML snippet:

<div ng-app="licenceApp" ng-controller="licenceController">    
    <div class="hover panel" ng-class="{switch : licenceFormVisible}">
        <div class="highlightedSection nosidepad clearfix back">  
            <div class="highlightedSubSection" ng-class="{fullsize : uploadModel.active}" ng-show="!Applying && !FinishedWithErrors && !offlineActivationScreenVisible">
                <h2>Licence File</h2>
                Upload and apply a valid licence file{{uploadModel.active}}<br /><br />
                ...
                <form id="hiddenUploadForm" name="hiddenUploadForm" target="hiddenUploadFormFileTarget" action="/settings/uploadILP" method="post" enctype="multipart/form-data" style="display: none;">
                    <input id="hiddenUploadFormFile" name="file" type="file" ng-model="uploadModel.uploadFileName" onchange="angular.element(this).scope().uploadFileChanged()" />
                    <iframe id="hiddenUploadFormFileTarget" name="hiddenUploadFormFileTarget" iframe-onload="uploadFileFinished()"></iframe>
                </form>
            </div>
        </div>
    </div>

ViewModel

angular.module('licenceApp.controllers', [])
    .controller('licenceController', ['$scope', 'licenceAPIservice', '$filter', '$timeout', function ($scope, licenceAPIservice, $filter, $timeout) {
        $scope.uploadModel = {
            active: false,
            uploadFileName: "",
            uploading: false
        };

        $scope.uploadFileChanged = function () {
            $scope.uploadModel.active = true;
            $scope.uploadModel.uploading = true;

            $('#hiddenUploadForm').submit();
        }
        ...

Despite changing uploadModel.active in a function and confirming it with a console.log, the display does not reflect the updated value. Could this still be due to prototypal inheritance? Note that uploadFileChanged is called when the input file control is changed.

Answer №1

When dealing with the onchange event in JavaScript outside of Angular, you will need to use the $apply method to inform Angular of any changes in the scope. Luckily, there is an Angular directive that makes this process easier (ng-change).

<input id="hiddenUploadFormFile" 
       name="file" type="file" 
       ng-model="uploadModel.uploadFileName"
       ng-change="uploadFileChanged()" />

UPDATE:

It's important to note that ngModel does not work with input type="file" (issue), therefore ngChange will not function as it requires ngModel.

The appropriate solution is to include $apply within your uploadFileChanged function.

HTML:

<input id="hiddenUploadFormFile" 
       name="file" type="file" 
       onchange="angular.element(this).scope().uploadFileChanged()"/>

JS:

    $scope.uploadFileChanged = function () {
        $scope.$apply(function() {
          $scope.uploadModel.active = true;
          $scope.uploadModel.uploading = true;
          $('#hiddenUploadForm').submit();
        });
    }

If you intend to use input type="file", consider creating a simple directive that manages the change event without the need to access the element scope in this manner.

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

Upgrading from Angular 1.2.x to 1.3.x resulted in a malfunction in the rendering of a webpage by the PhantomJsDriver (GhostDriver)

Following the update of our client Angular version from 1.2.8 to 1.3.5 (or testing other 1.3.x versions), a particular web page in the SUT started failing to render completely. The error message displayed was: [ERROR - 2015-03-22T08:28:04.332Z] Session ...

Tips for creating a responsive image using Material-UI

I’m facing some challenges in making my page responsive. Specifically, I'm having trouble ensuring that an image remains within the grid container in material UI. Is there a method for making images responsive in this context? Even when I try adding ...

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

The JavaScript string in question is: "accepted === accepted && 50 > 100". I need to determine whether this string is valid or not by returning a boolean answer

I am developing a dynamic condition builder that generates a JavaScript string such as, tpc_1 === accepted && tpc_6 > 100 After the replace function, the new string becomes, accepted === accepted && 50 > 100 Now my challenge is to va ...

Error: JSON parsing encountered an issue with token "o" at position 1 while making an ajax request

When I try to make an AJAX call, my code is set up like this: var Data = { name : $('input[name=name]').val(), email : $('input[name=email]').val(), phoneno : $('input[nam ...

React, Redux, Thunk - the trifecta of powerful

After spending a considerable amount of time struggling with this particular piece of code, I have scoured online resources such as Stack Overflow and the documentation, but there is still something that eludes me... The code in question revolves around t ...

When using promises in Vue, you can expect to receive an observer object

In my Vue.js project, I am trying to trigger a Vuex action in the created() lifecycle hook and then proceed to call an asynchronous method to fetch more data from the server upon receiving the initial data. The goal is to utilize this data in a component ...

allowChoosing and uiGridEnums

I'm attempting to make rows selectable based on a specific $treeLevel value. When I ran the code, I encountered a ReferenceError: uiGridConstants is not defined. I must confess that I am uncertain about the purpose of uiGridConstants. Below is the c ...

Showing submenu items in a jQuery menu system without causing the top level menu item to expand and fit

I currently have a menu system in place, which is quite simple, but there is an issue where the submenu items are larger than the top-level items. When hovering over the submenu items, the top-level menu expands to accommodate them. Is there a way to keep ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Choose a possibility that exceeds mere presentation

When using the select tag to display a dropdown, I am using ng-repeat in the option tag. If the ng-repeat contains a long string with a maxlength of 255 characters, how can I break it into lines to prevent overflow on the screen? Check out this screenshot ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Construct a structure containing the key/value pairs of cells within an HTML table row using JavaScript

I'm completely new to JavaScript so please be patient with me; I'm not even sure if I'm searching for the solution correctly. Despite spending hours googling and experimenting, I still can't get it to work. My issue is related to an HT ...

Issue with Importing AdapterDateFnsV3 in MUI?

I have the listed npm packages installed: "@mui/icons-material": "^5.15.19", "@mui/lab": "^5.0.0-alpha.170", "@mui/material": "^5.15.19", "@mui/system": "^5.15.15", "@mui/ ...

Having all elements at the same height

I am looking to enhance my JavaScript code to only impact 4 items at a time. The goal is to target the first 4 instances of .prodbox, adjust their height accordingly, then move on to the next set of 4 and repeat the process. This sequential adjustment will ...

What is the best way to retrieve a JSON element obtained from a Parse.com query?

I'm encountering difficulties when attempting to access a specific JSON element that I receive in response from a query made into a Parse.com Class. Despite reading through various questions and answers on similar topics, I have yet to find a solutio ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

JavaScript: utilizing JSON, implementing dynamic methods for creatures, and utilizing closures for encaps

Apologies for the unclear title, but I am unsure where the issue lies. Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters. Here is an e ...

The synergy of Sails, Angular, and Jasmine combined creates a

Utilizing SailsJS for the backend and Angular for the frontend has been a successful combination thus far. I have already implemented Mocha tests for the backend logic in SailsJS and now I am looking to add some tests for the frontend Angular code. Howeve ...