Unable to access the length of a scope variable after it has been modified

Within my HTML markup, I have a ng-init="find()" which triggers this particular function:

$scope.find = function()
{
    $scope.vehicles = Vehicles.query();
    $scope.vehiclesQtd = $scope.vehicles.length;
};

The issue arises when even though the vehicles are successfully displayed in the view, the value of $scope.vehiclesQtd is consistently showing as 0.

To address this, I implemented a watcher to update $scope.vehiclesQtd whenever a vehicle is added or removed:

$scope.$watch('vehicles', function()
{
    $scope.vehiclesQtd = $scope.vehicles.length;
    console.log(JSON.stringify($scope.vehiclesQtd, null, 4));
});

Despite this effort, the console keeps reporting a value of 0 for $scope.vehiclesQtd and an empty array for $scope.vehicles, even though the vehicles are visibly rendered on the screen. This information is crucial for setting a limit on creating new vehicles.

Answer №1

When you use

$scope.vehicles = Vehicles.query();
in your code, it is making an asynchronous HTTP call to fetch data. This means that the line
$scope.vehiclesQtd = $scope.vehicles.length;
is being executed before the HTTP call is completed.

To ensure you get the correct length of the array, you need to add an if statement in your watcher function. This will make sure that the length is only calculated after the HTTP call has finished and the data is returned to $scope.vehicles.

$scope.find = function(){
    $scope.vehicles = Vehicles.query();
    $scope.vehiclesQtd = $scope.vehicles.length;
};

To fix this issue, you can modify your watcher like this:

$scope.$watch('vehicles', function(newVal,oldVal){
     if(newVal !== oldVal){
         $scope.vehiclesQtd = $scope.vehicles.length;
         console.log(JSON.stringify($scope.vehiclesQtd, null, 4));
     }
});

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

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

Exploring Protractor functionality by testing ui-bootstrap-alert with the dismiss-on-timeout attribute

When running my protractor test, I encountered an issue where an alert is displayed when an error occurs in the app. Here is a snippet of the relevant HTML: <uib-alert type="danger" dismiss-on-timeout="5000" close="closeAlert()"> <span>Err ...

Manage both React keyboard and mouse events within a single function

I'm working on enhancing the accessibility of my web app by making it keyboard accessible. However, I am facing an issue when trying to handle both click and keyboard events using the '|' symbol in my function: Property 'key' does ...

The event listener $(window).on('hashchange', function() is causing issues on my Internet Explorer 9 browser

My website utilizes the code $(window).bind('hashchange', function ()) to check if a redirect is necessary. It is working perfectly fine in Firefox, but I am facing issues with IE9. $(window).bind('hashchange', function () { ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

Guide on making a Vertical Navigation Menu

Check out this menu designed with HTML and CSS. The menu items are currently displayed horizontally, but the submenus use a vertical layout. How can we modify the main menu items to also be arranged vertically? <ul> <li> <a>item1 ...

Tips for updating JS and CSS links for static site deployment

As I develop my static site using HTML files served from a simple web server, I want to use local, non-minified versions of Javascript code and CSS files. However, when it comes time to deploy the site, I would like to refer to minified versions of these s ...

Utilizing Tween for camera animation

Currently, I am attempting to smoothly adjust the camera's rotation in order to focus on a specific object within a graph. Up until now, my implementation includes: fourd.render_loop.push(() => TWEEN.update()); fourd.intersect_callback = functio ...

Generating Bootstrap v3 alerts that can be easily dismissed while integrating error rendering with Redux-Form

I am currently working with redux-form (v6.5.0) and have the following source code: class MyForm extends Component { render() { const {error} = this.props return ( <form> <Field.....> ...

Ways to troubleshoot the logic issue in the loop for my simple login interface

I have been able to successfully implement code that detects when a user enters an incorrect username or password, as well as granting access when the correct credentials are provided initially. However, there seems to be a logic error in my loop that prev ...

What is the best way to find information in a multi-page table?

I've implemented a table with pagination and search functionality to look up data within the table. However, currently the search only works within the current page of the table rather than searching the entire dataset. Is there a way to modify the se ...

Utilizing ng-click and ng-switch during the submission of an Angular form

I am working on a single-page Angular app where the landing page is a sign-in form with a link to a sign-up form. The rest of the app remains hidden until the user has been authenticated. To switch between the sign-in and sign-up pages, I am using the ng ...

Encountering the "Invalid JSON primitive" issue when making an AJAX request in MVC

Despite my efforts to resolve the "Invalid JSON primitive" issue by reading various references, I have not been able to find a solution. As a last resort, I am sharing my code in its simplest form and still encountering the error. See below for the minimal ...

How to make a JQuery list item unselectable when appending it

I encountered a strange issue while using jQuery to append items to a list. <ul id="idNicheItems" class="clScrollItems ui-widget-content ui-corner-all"> <li id="NicheItem_1"> Item 1</li> <li id="NicheItem_2"> Item 2</li& ...

Is there a compatibility issue between Vue particles and my project?

Greetings to all! I recently added Vue Particle to my Vue project, but encountered an issue while importing VueParticles in the Main.js file. Here is a snapshot from my terminal for reference. https://i.stack.imgur.com/Bxh2r.png ...

Conclude the execution of promises after a for loop

I'm looking to enhance my code by ensuring that it waits for the asynchronous query called prom to finish before resetting the array and restarting the first for loop. This way, the array will be cleared before the loop begins again. items = []; var ...

Arranging an array of objects by their unique identifiers

Given an array of objects containing root and list elements in a tree structure, how can I efficiently organize them into a tree with an unknown depth? Each object has a parent element ID property. I am currently working on building a menu. While I have s ...

Is there a way for me to incorporate a function in this script that allows for cycling through URLs in a predetermined order by clicking a button?

Is it feasible to incorporate a click button cycle URL function that alternates between URLs in a specified order to this script? <script type="text/javascript> var urls = new Array(); urls[0] = "google.com"; urls[1] = "amazon.com"; var random = M ...

Ways to enable a file download to a user's computer when a specific HTML button is clicked

<button type="submit" class="myButton" onclick="window.open('test.txt')">Cash Machine</button> This code is not functioning as expected when clicked. The desired action is to prompt the download of test. ...