What could be causing the custom filter to malfunction in AngularJS?

I am struggling to display sorted data using ng-repeat. Although I looked at this example for guidance

Order by Object key in ng-repeat

applying the same filter did not yield the desired output. My list remains unsorted.

You can view my code here: http://plnkr.co/edit/qFaBYnwCVTZJZSiw6hdD?p=preview

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

    app.controller('MyCtrl',function($scope){
       $scope.lines = {
            "a": {name:"bb"},
            "aa":{name: 'aa'},
            "zz": {name:"zz"},
            "oo":{name: 'oo'}, 
            "kk": {name:"k"},
            "j":{name: "a"},
            "n": {name:"n"},
            "c":{name: "c"}
        }
    })

    app.filter('toArray', function() { 
        return function(obj) {
            if (!(obj instanceof Object)) return obj;
            return _.map(obj, function(val, key) {
                return Object.defineProperty(val, '$key', {__proto__: null, value: key} );
            });
        }
    });

Answer №1

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

app.controller('MyCtrl',function($scope){
   $scope.lines = {
     "a": {name:"bb"},
    "aa":{name: 'aa'},
    "zz": {name:"zz"},
    "oo":{name: 'oo'}, 
    "kk": {name:"k"},
    "j":{name: "a"},
    "n": {name:"n"},
    "c":{name: "c"}
};
  
  $scope.myFilter = function(){
    var array=[];
    angular.forEach($scope.lines,function(value,key){
       array.push(value);
      });
    return array;
    
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="(key, line) in myFilter() | orderBy:'name'">
      <div class="preview">{{line.name}}</div>
   </div>
   </div>

try this. make sure to use object property for orderBy.

   <div ng-repeat="(key, line) in lines | toArray | orderBy:'name'">

Edit

you can utilize filter in the controller like below

  $scope.myFilter = function(){
   var array=[];
   angular.forEach($scope.lines,function(value,key){
   array.push(value);
  });
  return $filter('orderBy')(array, 'name');
 }

remember to inject the filter service to use the filter.

  app.controller('MyCtrl',function($scope,$filter){

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

Testing a service with $resource using unit tests

Struggling to write a unit test for an existing service and puzzled by the unexpected data appearing in the results, leading to test failures. Let's take a look at the key components: Service Method: function createAddressType(newAddressType) { var ...

Alphabet Frequency Chart: Counting the occurrences of each letter in a given string (even if it is 0)

I have developed a function that generates an array showing the frequency of each letter in the alphabet (a-z) within a given string, including 0 occurrences. The array consists of 26 numbers representing each letter of the alphabet. Here is the function ...

Scrollbar missing in browser

I'm currently working on an HTML page, and I've encountered an issue where the browser scrollbar doesn't appear when the content exceeds the browser window. My CSS skills are at a beginner level, so I'm not entirely sure how to add attr ...

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

Obtain the predecessor of the element that was clicked

I have a complex structure with nested tables, rows, and cells, each containing div elements with multiple spans. I am trying to create a function that will capture the clicked cell every time I click on either the cell itself or any of its child elements ...

requiring a page reload for an AJAX-loaded webpage

Encountering an issue with a third-party integration on a website specifically designed for iPads, where multiple pages are loaded using AJAX. Upon visiting the page for the first time, the expected functionality is missing and only appears after refreshi ...

rearrange elements in the HTML code

I need to display 3 tables, each with a width of 300px, on a webpage. These tables can be collapsed or visible. My goal is to arrange them so that if only one table is visible, it appears in the center of the page (centrally aligned). Additionally, the tab ...

Adjust the size of divs using JQuery UI's draggable feature

Looking for a way to make two divs share 100% of their parent's width, with a dynamic resizing feature in between them? Check out my solution here: http://jsfiddle.net/aRQ7a/ However, I'm facing an issue where when I decrease the size of the pre ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Using vanilla JavaScript to close a modal in Bootstrap 5 is a great way

Hello, I recently came across a tutorial which discusses how to show a modal in Bootstrap 5 using JavaScript. The tutorial can be found at the following link: https://getbootstrap.com/docs/5.0/components/modal/#via-javascript. In the tutorial, they demonst ...

Updating a table dynamically after a form submission using jQuery, Ajax, and PHP without needing to refresh the page

My current setup involves an ajax form along with a table. Here is the ajax code I am using: $(function () { $(".submitann").click(function () { var title = $("#title").val(); var announcement = $("#announcement").val(); var d ...

The push() function is triggering an error where db._checkNotDeleted is referenced incorrectly as a

I'm attempting to save an object in the database. Here's the code snippet I've been using: app.post('/newOrderWithObject', (req, res) => { var msg = {"name":"Harry"}; push(ref(db,"test/orders&qu ...

Emails not being sent by Nodemailer, showing a message of 'Message sent: Undefined'

Initially, everything was working fine but suddenly it stopped. I tried sending some emails and then it just stopped with an error message "Message sent: Undefined". Additionally, I encountered the following error message - (node:9048) UnhandledPromiseReje ...

How to append a new key to an array of objects using JavaScript

I have encountered a small issue while trying to add the key 'greeting' to an array of objects. Although my code successfully adds the key, it also adds another array at the end when I log the result. function greetDevelopers(list) { list.greet ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

How can I pass the dynamically generated ID from PHP to AJAX/jQuery using an anchor tag?

I'm seeking help with jQuery and Ajax as I am new to it. My issue is that I have multiple 'edit' buttons in a table, one for each row's data. When I click on an edit button to modify the data, they all open at once instead of just the s ...

Issue with Angular Bootstrap UI Typeahead functionality when implementing async loading approach

I am currently facing a minor issue with the Typeahead directive in my code. Here is what I have tried so far: $scope.getUserNames = function (input) { return $http.get(ApplicationConstants.apiUrl + 'api/Users/UserNames', { ...

Simple Bootstrap Input Slider Configuration

I am attempting to create a simple setup for a bootstrap-style input slider, but I am facing some difficulties getting it to function properly. Desired Outcome: https://i.sstatic.net/Btfo3.png Actual Outcome: https://i.sstatic.net/0VnNv.png Resource / ...