What is the best way to apply a filter to an angular directive for filtering data in an ng-repeat loop?

Having some trouble setting up a directive where I can pass both the data and a specific filter to be used in the ng-repeat. My current approach doesn't seem to be working, so I might need to rethink my strategy.

Any suggestions on how I can pass in the filter? Alternatively, is there a way to prefilter/sort the list before passing it in?

(It's important that the scope remains isolated, as I need to have multiple lists on the same page.)

<!DOCTYPE HTML>
<html ng-app="MyApp">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script>
var myApp = angular.module('MyApp', []);
myApp.controller('mainPage',function($scope){
    $scope.cars = ["Saab","Volvo","BMW"];
    });
myApp.directive('carList',function(){
    return {
        scope: {
        listOfCars: '=',
        carFilter : '@'
        },
        restrict: 'E',
        replace: 'true',
        template: '<table>\
    <tr ng-repeat="{{carFilter}}">\
    <td>{{car}}</td>\
    </tr>\
    </table>'
    };
});
    </script>
</head>
<body ng-controller="mainPage">
<car-list list-of-cars="cars" car-filter='car in listOfCars | orderBy:"toString()"' ></car-list>
</body>
</html>

Check out the Plunker link with the code above: http://plnkr.co/edit/ipsF15?p=preview

Answer №1

After giving it some thought, I believe I have come up with a viable solution. Instead of passing in the filter, passing in the already filtered list seems to be a better option:

<!DOCTYPE HTML>
<html ng-app="MyApp">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="angular.min.js"></script>
    <script>
var myApp = angular.module('MyApp', []);
myApp.controller('mainPage',function($scope){
    $scope.cars = ["Saab","Volvo","BMW"];
    });
myApp.directive('carList',function(){
    return {
        scope: {
        listOfCars: '&',
        },
        restrict: 'E',
        replace: 'true',
        template: '<table>\
    <tr ng-repeat="car in listOfCars()">\
    <td>{{car}}</td>\
    </tr>\
    </table>'
    };
});
    </script>
</head>
<body ng-controller="mainPage">
<car-list list-of-cars="cars | orderBy:'toString()' | limitTo:2 " ></car-list>
</body>
</html>

Although this approach may not seem very intuitive at first glance, I believe it is the right way to go. What are your thoughts on this?

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

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

Deciphering occurrences in highcharts

When drawing a rectangle in highcharts using the selection event, I am able to retrieve the coordinates of the box by translating the axis values of the chart like this: chart.xAxis[0].translate((event.xAxis[0]||chart.xAxis[0]).min) Now, my query is how ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...

What is the best way to focus on a specific section of a CSS class name?

Successfully Working Example: HTML: <div class="items"> <div class="item">item 1</div> <div class="prefix-item-suffix">item 2</div> <div class="item">item 3</div> < ...

Identifying periods of inactivity using an embedded iframe

I have developed a website that showcases a three.js model within an iframe. My goal is to redirect users back to the homepage (index.html) after they have been inactive for a specified amount of time. While I have managed to achieve this using JavaScript, ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Unexpected behavior with async pipe - variable becomes undefined upon reassignment

In my development process, I have implemented 2 components. One is responsible for fetching data from an external service, while the other one displays this data. The constructor of the first component is structured as follows: constructor( private dev ...

Ways to display additional information in typeahead using Angular JS

Currently, I am using the Bootstrap directory typeahead in Angular. I am looking to display more results in my HTML template instead of just the name: typeahead="job as job.name for job in getJobPlace($viewValue) | filter:{name:$viewValue}" I would like ...

Display a text box upon clicking an item

I've been curious about how to create the effect of a text box or div that appears when clicked on, similar to what you see in this. Scroll down and click on "show patchnotes"; I've been puzzled by this for a while but haven't come across a ...

Can someone help me adjust the height and width of my website for mobile in react js?

I'm still getting the hang of React JS and recently built a simple website. While it looks fine on a web browser, the mobile version is not quite right. The height on mobile appears to be double what it should be, resulting in a large scrollbar that s ...

Point the API endpoint to a different file

Is there a method to proxy a specific binary file, such as redirecting a PDF file to another PDF file using something like app.use('/proxy', proxy('/desiredPath'))? I have tried this approach, but it does not seem to work for the parti ...

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Can someone explain why my Laravel route is consistently showing a 404 error?

Currently, I am attempting to perform an AJAX request for a form post type. However, the PHP parse script I am trying to send the data to is returning a 404 error as observed through Chrome developer tools. Below is the code snippet: <script type="text ...

The export "hasInjectionContext" is not provided by the source file "node_modules/vue-demi/lib/index.mjs", but it is being requested in the file "node_modules/pinia/dist/pinia.mjs"

Every time I launch my program, the console displays an error message stating that "hasInjectionContext" is not exported by "node_modules/vue-demi/lib/index.mjs", imported by "node_modules/pinia/dist/pinia.mjs" at line 6:9. I ...

Clicking on a button in Angular UI-grid will allow you to edit the

I am currently utilizing Angular in conjunction with UI-Grid () The Grid has been configured using the options provided below this.mdGridLogOptions.gridOptions= { enableSorting: false, enableColumnMenus: false, enableAutoFitColumns: false, paginationPage ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

I'm looking to add autocomplete functionality to a text input in my project, and then retrieve and display data from a MySQL database using

Looking to enhance user experience on my form where users can select inputs. Specifically, I want to implement a feature where as the user starts typing in a text input field with data from a MYSQL database, suggestions will be displayed. The form is locat ...

Can WebDriverJS be compiled without code minimization using Google Closure Compiler?

I am in need of customizing WebDriverJS to suit my specific requirements. However, I am encountering difficulties with debugging the compiled source code. Having descriptive function names and comments would greatly assist me! Therefore, I am curious to kn ...