Displaying Angular table rows with missing values (Error: Cannot access property 'length' of undefined)

In the view, I have a table displaying nested data using ng-repeat. I want to show only rows with empty cells (<textarea>) when a link is clicked to apply a filter. The text of the link should change to 'Show all data' so that clicking it again will revert back to showing all data.

<a class="btn btn-primary" href="#" ng-click="view.applyMissingValuesFilter(view.missingValuesButtonText)">{{view.missingValuesButtonText}}</a>

<table class="table">
    <tr>
        <th>Resource Id</th>
        <th ng-repeat="locale in view.resourceGridResources.Locales">
            {{locale ? locale : "invariant" }}
        </th>
    </tr>
    <tr ng-repeat="resource in view.resourceGridResources.Resources">
        <td>{{resource.ResourceId}}</td>
        <td ng-repeat="res in resource.Resources">
            <textarea ng-model="res.Value"
                      ng-blur="view.saveGridResource(res)"
                      style="min-width: 300px"></textarea>
        </td>

    </tr>
</table>

I attempted the following logic in the controller to initially display rows with empty data:

vm.applyMissingValuesFilter = function (linktext) {

        var results = [];

        var temp = vm.resourceGridResources.Resources;

        for (var i = 0; i < temp.length; i++) {
            for (var j = 0; j < temp[i].resources.length; j++) {
                if (temp[i].resources[j] === '') {
                    results.push(temp[i]);
                }
            }
        }

        console.log(results);

        linktext === "Display Rows with missing data"
            ? vm.missingValuesButtonText = "Show all data"
            : vm.missingValuesButtonText = "Display Rows with missing data";

    };

An error occurred:

TypeError: Cannot read property 'length' of undefined
   at listController.vm.applyMissingValuesFilter (listController.js:67)
   at fn (eval at compile (angular.js:13275), <anonymous>:4:442)
   at f (angular.js:23481)
   at n.$eval (angular.js:15922)
   at n.$apply (angular.js:16022)
   at HTMLAnchorElement.<anonymous> (angular.js:23486)
   at HTMLAnchorElement.dispatch (jquery.js:4430)
   at HTMLAnchorElement.r.handle (jquery.js:4116)

If I simply do something like console.log(temp.length), it outputs the correct length.

Alternatively, is there a simpler way to achieve this? I thought about using regular expressions, such as

<td ng-repeat="res in resource.Resources" | match: ^$
, but I believe there might be a better solution using filters?

Answer №1

The name of your object is Resources, not resources.

Please update temp[i].Resources instead of temp[i].resources in the second loop and make sure to change this line temp[i].resources[j] to temp[i].Resources[j]

  for (var i = 0; i < temp.length; i++) {
            for (var j = 0; j < temp[i].Resources.length; j++) {
                if (temp[i].Resources[j] === '') {
                    results.push(temp[i]);
                }
            }
        }

EDIT:

You might also want to modify temp[i].resources[j]==='' to temp[i].resources[j].Value===''

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 removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Dealing with data manipulation in the realm of javascript

In the following code snippet, I am iterating through multiple URLs and extracting data (title and content) from each of them. My objective is to store this data for later use on another page, and thus it needs to be accessible using its respective title, ...

Clearing LocalStorage and Cache upon initial loading in Next.js

Our project requires continuous updates, and currently users are required to manually clear their cache and localStorage data after each update in order to access the new features. Is there a solution to automatically clear all cached data upon user visi ...

Leverage the power of Angular 2 components within your Asp.net MVC

I am currently working on an Asp Mvc project which utilizes Angular 1.4 for the frontend. While my project is not designed to be a single page application, I am interested in incorporating Angular 2 without transitioning the entire project into a SPA. Aft ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

Issue with CSS: 200vw not scaling correctly for mobile devices

I'm attempting to create a horizontal slide effect between two div elements, so here is the HTML code: <div id="container"> <div class="viewport-1"> <div class="inner-div"> <h1>Viewport background 1</h1></ ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

What are the steps for utilizing the map function to merge an array or nested array into a div element?

I'm currently developing a recipe box application and have shared the code pen for it: http://codepen.io/capozzic1/pen/gmpVyr?editors=0110. The code snippet is as follows: class RecipeList extends React.Component { constructor(props) { super(p ...

Using an array as a parameter in Angular Resource's update method

After weeks of searching on Google, I still haven't found a solution to my problem. Although someone might consider this a duplicate, I believe it's a unique issue. Here's the situation: I'm currently using Angular in a node-webkit ap ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

What is the best way to display label information on a Google line chart?

line graph column graph My graph continuously calls the Controller to fetch recent data from the Database. There are two lines on the graph, and I would like to display the names of each line (column) such as red=counts of something // brown=counts of so ...

Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable: @Injectable() export class ProductService { getAllProducts(): Observable<Product[]> { return this.http.get(' ...

Troubleshooting issue with default button in asp.net using javascript

Despite my best efforts, I couldn't figure out how to make a button default until I came across a helpful tip from someone here who shared some javascript code that checks for the enter key in a textbox and triggers the button. I attempted placing my ...

Encountering a parsing issue within my React program

I keep encountering a parsing error while trying to run my React application The compilation fails with the following error message: ./src/App.js Line 7: Parsing error: Unexpected token, expected "{" After reviewing my code, I couldn't find any unex ...

Concealing URL in client-side fetch request within Next.js

A contact form built in Next.js makes use of the FormSubmit API to send emails upon clicking the submit button. Below is the code for the onSubmit handler: const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch("https:/ ...

angularDynamicLocation does not contain the specified localeLocationPattern

I am using angular-translate to handle localization with angular dynamic localization. I have attempted the following code, but for some reason the localization is not changing. I suspect that the issue lies in angular not being able to locate localeLocati ...

Troubleshooting a malfunctioning custom controller in AngularJS

<html ng-app> <head> </head> <body data-ng-controller="Myfunc"> <ol type="i"> <li data-ng-repeat="c in cust | filter:name"> {{ c.name | lowercase}} - {{c.city | lowercase}}</li> </ol> ...

Constructing a JSON schema for a dynamic aggregate query

Looking to create a query that matches fields with data in them. Here is an attempt: var matchStr = {}; if (received.user) { matchStr = { "_id": { "$regex": received.user, "$options": "i" } }; } if (received.name) { matchStr += { "name": { " ...