The data does not display when using ng-repeat in AngularJS

I created a filter using AngularJS but I am experiencing some issues with displaying the information.

Although the filter is functioning correctly (you can verify by checking '$scope.showItems.length' which shows that it returns data), when I select the option "BUCURESTI" to display it using 'ng-repeat', no data is shown even though it exists in '$scope.showItems'.

Only when I choose the "Selectati judetul" option does the data appear.

Does anyone know where the problem lies?

Here is the Plnkr link: https://plnkr.co/edit/NYruIfo3GXLLmcs4jfpe?p=preview

HTML:

<body ng-app="salariesApp" ng-controller="mainCtrl" class="my-gray">
    <div class="container" ng-controller="searchCtrl">
        <table class="table table-bordered-top-bottom table-hover show-table">
            <tr>
                <td class="tableSearch"><input class="tableSearch spa-search8 form-control" type="text" id="inputName" ng-model="searchSal.den" /></td>
                <td class="tableSearch">
                    <select class="tableSearch spa-search6 form-control" id="inputJudName" ng-model="searchSal.jud" ng-options="jud for jud in jduete"
                                    ng-change="searching('jud')" >
                        <option value="">Selectați județul</option>
                    </select>
                </td>
            </tr>
            <tr ng-repeat="rows in showItems | filter: searchSal">
                <td>{{rows.den}}</td>
                <td ng-show="false">{{rows.tip}}</td>
                <td>{{rows.jud}}</td>
            </tr>
        </table>
        <br/>
        <input class="tableSearch spa-search8 form-control" type="text" ng-model="out" />
    </div>
</body>

App & Services:

var app = angular.module('salariesApp', []);

app.factory('salServ', ['$http', 'appConst', function ($http, appConst) {
    var showSal = {};
    showSal.ddrm = appConst.defaultDiacriticsRemovalMap;

    // Remove diacritics from strings
    var changes;
    showSal.removeDiacritics = function (str) {
        if (!changes) {
            changes = showSal.ddrm;
        }
        for (var i = 0; i < changes.length; i++) {
            str = str.replace(changes[i].letters, changes[i].base);
        }
        return str;
    }

    return showSal;
}]);

Controllers:

app.controller('mainCtrl', ['$scope', '$window', 'appConst', 'salServ',
                            function($scope, $window, appConst, salServ) {  
    $scope.showSalTh        = appConst.showSalTh;
    $scope.jduete               = appConst.judArr;
    $scope.sectoare         = appConst.sectArr;
    $scope.showSal          = appConst.salArr;

    $scope.searchSal = {};
}]);

app.controller('searchCtrl', ['$scope', '$filter', 'appConst', 'salServ',
    function($scope, $filter, appConst, salServ) {
    $scope.out = "";

    $scope.showItems = $scope.showSal;
    $scope.searching = function(initParam) {
        $scope.$watch('searchSal', function() {
            if (initParam == 'jud') {
                if ($scope.searchSal.jud == null) {
                    delete $scope.searchSal['jud'];
                    console.log('del');
                }

                var functionFilter = function (actual, expected) {
                    if (typeof actual === 'string') {
                        var cleanValue = salServ.removeDiacritics(actual).toLowerCase();
                        var searchCleanText = salServ.removeDiacritics(expected).toLowerCase();
                        var boolChk = cleanValue.includes(searchCleanText);
                        
                        return boolChk;
                    }
                }
                $scope.showItems = $filter('filter')($scope.showSal, $scope.searchSal.jud, functionFilter);

                console.log($scope.showItems);
                console.log($scope.showItems.length);
                $scope.out = '$scope.showItems.length = ' + $scope.showItems.length;
            }
        });
    };
}]);

Constants:

app.constant("appConst", {
    judArr: ["BUCUREȘTI", "Alba", "Arad", "Argeș", "Bacău"],
    salArr: [
        { den: 'Oracle Romania', jud: 'Bucuresti'},
        { den: 'Oracle Romania', jud: 'Bucuresti'},
        { den: 'Oracle Romania', jud: 'Bucuresti'},
        { den: 'Microsoft', jud: 'Bucuresti'},
        { den: 'Microsoft', jud: 'Bucuresti'},
        { den: 'Computer Generated Solutions - CGS Europe', jud: 'Bucuresti'},
        { den: 'Computer Generated Solutions - CGS Europe', jud: 'Bucuresti'}
    ],

    defaultDiacriticsRemovalMap: [
        {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2...]
});

Answer №1

It appears that the issue lies in filtering your data twice, once in the html and again in your controller within 'searchCtrl' inside the $watch function. To resolve this, simply remove the filter from the html since 'showItems' already contains filtered data.

Make the following replacement:

<tr ng-repeat="rows in showItems | filter: searchSal">

with:

<tr ng-repeat="rows in showItems">

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

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

Utilizing the $.ajax method along with the onreadystatechange event

Is there a way to use the onreadystatechange event of the underlying XMLHttpRequest in JQuery's (version 2.0.2) $.ajax(...) function to trigger synchronous ajax requests for displaying accurate status indications during long-running processes? It seem ...

Execute javascript function upon user scrolling to a designated section in the webpage

Is there a method to trigger a unique function every time a user scrolls to a different div or section of the page? ...

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...

Display the user's username on the navigation bar once they have successfully

I am having trouble displaying the username after logging in on the navbar. After logging in with the correct credentials, I am redirected to the page, but the navbar doesn't update with the username. Can someone provide some tips on what I should do ...

Why is my React-Redux API Get request action not running?

Hello there! I am currently working on integrating React-Redux with my Flask API to display JSON data on my website. Although the API is functioning properly, I seem to be facing an issue where the action called does not execute. As a beginner in Redux, I ...

Exploring the Combination of Conditional Rendering and Redux within the App.js File

Currently, I am in the process of setting up an authentication flow with Redux in my application. To control the display of either the app screen or the authentication screen, I have implemented conditional rendering in my App.js file. Here is the snippet ...

Using TypeScript to extend functionality from Array

I am currently working on designing a robust data model for an AngularJS application, and I am interested in having my model inherit from Array<BaseModel>. However, I have not yet discovered a foolproof way to accomplish this. In a hypothetical scen ...

When you click on `window.open('my-app://', '_blank');`, it won't directly open the desktop app from the browser. However, typing `my-app://`

When I open Chrome and enter my-app:// in the URL or search bar, a dialog box pops up saying "Open my-app? A website wants to open this application". Clicking ok opens my Electron app. I'm looking to add similar functionality to my React app, where t ...

Setting a cookie in a browser using an AJAX response: A step-by-step guide

When utilizing a Javascript function with jQuery to send a POST request to a web service, the response from the web server includes a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", along with a JSON body. However, despite this expected ...

Leveraging the `instanceof` operator within AngularJS expressions

Can I utilize the "typeof" method in AngularJS? I am using ngRepeat to iterate through my data and need to determine whether each item is a string or an object. <tr ng-repeat="text in data"> <td>{{angular.isObject(text) && 'IsObject& ...

Manage the border around the image by incorporating a timer countdown - starting from a complete circle, transitioning to a partial arc, and finally disappearing completely

My expertise lies in html, css, and angularjs for front-end development. I have an image that is initially surrounded by a thick border forming a full circle. As a countdown of one minute begins, I want the border to gradually disappear as time progresses. ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

Having trouble toggling the dropdown submenu feature in a Vuejs application?

.dropdown-submenu { position: relative; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-top: -1px; } <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorial ...

What is the best approach for re-running controllers once the global data has been resolved?

Upon loading the application, I retrieve data within a run block... .run(function($rootScope, $q, teams, schools, news, games){ // Fetch all relevant data $rootScope.showSplash = true; $q.all([ $rootScope.school = schools.get({id:1}), $root ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

Upon loading, the Carousel is visible instead of being hidden, which is contrary to its intended behavior

Any help would be greatly appreciated as I am struggling with creating a web page featuring tabs for "London, New York, Shanghai". The initial page displayed is the "welcome" page with the other tabs hidden on load. I successfully implemented a carousel f ...

The wonders of JSON.stringify() and the dynamic world of JavaScript Objects

Maybe I overlooked something in my JavaScript knowledge and I'm just realizing it now. I was experimenting with this code snippet in the Chrome console: a = []; a.name = "test"; JSON.stringify(a); // this returns [] a = new Object(); a.name = "test ...

Load Bootstrap 4 Modal with Ajax

I recently upgraded from Bootstrap 3 to Bootstrap 4.1 Within my applications, I utilize ajax loaded modals. In the layout, I have: <div class="modal fade" id="myModalToFillInfo" tabindex="-1" role="dialog" aria-labelledby="myModalToFillInfoLabel" ari ...