Issues with AngularJS Filters malfunctioning

After watching some AngularJS videos and attempting to apply a filter to a list of bookmark categories, I'm having trouble loading the main content. At the moment, I haven't implemented views in my code and would like it to remain view-less for now.

The issue arises with the filter line - when I remove the curly braces around it, the bookmark list shows up but the filtering still doesn't work!

Please advise on what corrections need to be made.

Below is the code for INDEX.HTML

<!doctype html>
<html ng-app="Eggly">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Eggly</title>

    <link rel="stylesheet" href="assets/css/normalize.css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <link rel="stylesheet" href="assets/css/eggly.css">
    <link rel="stylesheet" href="assets/css/animations.css">
</head>
<body ng-controller='MainCtrl'>
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-3 col-md-2 sidebar">
                <a href="#"><img class="logo" src="assets/img/eggly-logo.png"></a>
                <ul class="nav nav-sidebar">
                    <li ng-repeat="category in categories">
                        <a href="#" ng-click="setCurrentCategory(category)">{{category.name}}</a>
                    </li>

                </ul>
            </div>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">

                <div ng-repeat="bookmark in bookmarks | filter:{category:currentCategory.name}">
                    <button type="button" class="close">&times;</button>
                    <button type="button" class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span></button>
                    <a href="{{bookmark.url}}" target="_blank">{{bookmark.title}}</a>
                </div>

                <hr/>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script type="text/javascript" src="app/eggly-app.start.js"></script>
</body>

JS FILE

angular.module('Eggly', [

])
.controller('MainCtrl', function($scope){

$scope.categories = [
{"id": 0, "name": "Development"},
{"id": 1, "name": "Design"},
{"id": 2, "name": "Exercise"},
{"id": 3, "name": "Humor"}
];
$scope.bookmarks= [
{"id":0, "title": "AngularJS", "url": "http://angularjs.org", "category": "Development" },
{"id":1, "title": "Egghead.io", "url": "http://angularjs.org", "category": "Development" },
{"id":2, "title": "A List Apart", "url": "http://alistapart.com/", "category": "Design" },
{"id":3, "title": "One Page Love", "url": "http://onepagelove.com/", "category": "Design" },
{"id":4, "title": "MobilityWOD", "url": "http://www.mobilitywod.com/", "category": "Exercise" },
{"id":5, "title": "Robb Wolf", "url": "http://robbwolf.com/", "category": "Exercise" },
{"id":6, "title": "Senor Gif", "url": "http://memebase.cheezburger.com/senorgif", "category": "Humor" },
{"id":7, "title": "Wimp", "url": "http://wimp.com", "category": "Humor" },
{"id":8, "title": "Dump", "url": "http://dump.com", "category": "Humor" }
];

$scope.currentCategory = null;

function setCurrentCategory(category) {
$scope.currentCategory = category;
}

$scope.currentCategory = setCurrentCategory;


});

Answer №1

Your code has a few errors that need to be fixed.

  1. Make sure to attach .setCurrentCategory() to either $scope or this in the controller as Angular follows the MVVM architecture. $scope is an object that connects your controllers with views. If you want to interact with data from the controller using the method setCurrentCategory, you must assign it to $scope.

  2. Remember that filters, according to the AngularJS documentation, require expressions and not curly brackets.

angular.module('Eggly', [])
  .controller('MainCtrl', function($scope) {
    $scope.categories = [{
      "id": 0,
      "name": "Development"
    }, {
      "id": 1,
      "name": "Design"
    }, {
      "id": 2,
      "name": "Exercise"
    }, {
      "id": 3,
      "name": "Humor"
    }];
    $scope.bookmarks = [ ... ];

    $scope.currentCategory = null;

    function setCurrentCategory(category) {
      $scope.currentCategory = category;
    }

    $scope.setCurrentCategory = setCurrentCategory;


  });
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='Eggly'>
  <div ng-controller='MainCtrl'>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li ng-repeat="category in categories">
              <a href="#" ng-click="setCurrentCategory(category)">{{category.name}}</a>
            </li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <div ng-repeat="bookmark in bookmarks | filter:currentCategory.name">
            <button type="button" class="close">&times;</button>
            <button type="button" class="btn btn-link"><span class="glyphicon glyphicon-pencil"></span>
            </button>
            <a href="{{bookmark.url}}" target="_blank">{{bookmark.title}}</a>
          </div>

          <hr/>
        </div>
      </div>
    </div>
  </div>
</div>

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

Using the Tailwind CSS framework in combination with Vue's v-html

My vue component is designed to accept a prop of raw HTML, which originates from a wysiwyg editor utilizing tailwind classes for styling - similar to our vue app. The issue arises when using v-html="responseFromAPI" in my component, as the raw H ...

Troubleshooting a jQuery Selector Issue with a Dynamic Form

I developed a jQuery function to search for all the necessary inputs in a specific section of a website. function check_property_vars() { jQuery(this).parents('.property_group').find('div[id^="property_group_"]:input[required]:visible&a ...

It appears that the options attribute is being overlooked by the Angular toast directive

While working with Angular, I found the need for toast messages. In my search for answers, I came across an Angular Toast solution discussed in this question: Fire notification toaster in any controller angularjs However, when trying to set the location ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

Creating and downloading a Word document with Node.js by utilizing officegen

Recently, I've been trying to utilize the officegen npm module in order to generate a word (docx) file and then download it. Previously, I relied on the tempfile module to create a temporary path for the purpose of downloading. Below is the code snipp ...

The data display in MUI-Datatable is experiencing an issue where it is unable to read properties of undefined, specifically when trying to split the data

Whenever I include data within the MuiDatatable, it triggers this error: Cannot read properties of undefined (reading 'split') Is there a solution to this problem so that the data can be properly displayed? To demonstrate the issue, I have se ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Is it possible that an issue with ui-router is causing Angular to crash Chrome on a local machine?

Encountering a peculiar issue with AngularJS in a local Windows environment. Utilizing two Angular-based bootstrap frameworks, Homer and Neuboard (links: homer and neuboard). Running both templates on Chrome locally causes the browser to freeze and consume ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Setting URL parameters in a POST request: A guide

Currently, the data in question is structured as JSON within this code snippet. However, I've received feedback indicating that it should actually be implemented as URL parameters. I'm currently facing some difficulties with modifying this to fit ...

Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string. Suppose I have two checkboxes labeled: label1 and label2, my a ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

In the React js and emotion framework, fonts are only loaded in production mode after the page has been re

I have set up emotion's Global component to globally apply a font to my app: export const GlobalStyle: FC<{}> = () => ( <Global styles={css` @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;50 ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

In Chrome, there is a conflict between the screen width when using `position: absolute` and `position: fixed` if there is vertical

I'm in the process of developing a website with a video banner set to fixed positioning in the background, and a div that has absolute positioning covering part of the video on the bottom half. However, I've encountered an issue - when I add this ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...