Clear out duplicate elements from array instruction

I am currently working with a div that displays names and I need to remove any duplicates from my array. I have successfully achieved this with a filter, but now I would like to explore creating a directive to extend this functionality.

<div ng-controller="MainController">
        <ul>
            <li ng-repeat="name in names | unique">
                {{name}}
            </li>   
        </ul>
</div>

Below is the existing filter code.

angular.module('app')
    .controller('MainController', ['$scope', function($scope){
        $scope.names = ['a','b','c','d','a','c'];
    }])
    .filter('unique', function(){
        return function(names){
            var obj = {};
            names.forEach(function(name){
                obj[name] = null;
            })
            return Object.keys(obj);
        }
    })
    .directive('unique', function(){
        return {
            link: function(scope, elem, attr){

            }
        }
    })

I am seeking guidance on how to create a directive that will effectively remove duplicates from my array.

Answer №1

Here's my version:

const app = angular.module('app');
app.controller('MainController', ['$scope', function($scope){
    $scope.names = ['a','b','c','d','a','c'];
}]);
app.directive('uniqueArray', function(){
    return {
        restrict: 'E',
        scope: {
            arr: '='
        },
        template: '<ul><li ng-repeat="item in unique_arr">{{item}}</li></ul>',
        controller: function($scope){

            function getUniqueItems(items){
                let obj = {};
                angular.forEach(items, function(item){
                    obj[item] = null;
                });
                return Object.keys(obj);
            }

            $scope.unique_arr = getUniqueItems($scope.arr);
        }
    }
});

And in the HTML:

<unique-array arr="names"></unique-array>

In my opinion, using a directive here may be unnecessary since it acts more like a wrapper.

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

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

How to reference an image located in one folder from a page in a different folder using React

Imagine there is Folder A containing an image called 'image.jpg' and Folder B with an HTML page that needs to access the image in Folder A in order to display it. The following code successfully accomplishes this task: <img src={require(&apo ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

Change the function from onLoad to onClick exclusively

I'm experiencing a particle explosion on my webpage due to this code. I connected the onClick function to a button in my HTML so it executes only when that specific button is clicked. However, the function automatically runs when I load the HTML and ...

Steps for transferring data from a POST response to the client in NodeJS/ExpressJS

I am currently in the process of setting up an EasyPost API and I need to save some data that is included in a response from a POST route. My goal is to send this data directly to the client for storage, but I am struggling to determine where or how to do ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...

Experiencing an issue with Firestore returning null instead of data in JavaScript

I have created a form that, upon submission, adds a document with the data to my Firestore database. Additionally, I have set up a real-time listener on the collection where the document is added. onSubmit={async(e) => { e.preven ...

When using Laravel 5.2, JSON data is mistakenly returned as HTML

I've encountered an issue with ajax. My goal is to fetch all the records from a specific table using this ajax call: $('#chooseInvBtn').on('click', function(){ $.ajax({ type: "POST", url ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

The URL dynamically updates as the Angular application loads on GitHub Pages

Encountering an unusual issue when trying to access my angular website on GitHub pages. The URL unexpectedly changes upon opening the page. Please check it out at this link: The original expected URL should be However, as the page loads, the URL gets alt ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Disregard the JSON formatting and extract solely the values

After extracting data from an API, the format of the returned information looks like this: [{"id":21},{"id":22},{"id":24}] Next, I need to send this data to a database using a different API. However, the format for sending should be like this: [21,22,24] ...

Using jQuery to deactivate buttons upon submission or clicking within forms and hyperlinks

Within my Rails application, there are buttons that send data to the server. Some of these buttons are part of a form while others are standalone. I am seeking a solution to implement my jQuery code, which disables the buttons upon click, for both scenario ...

Reverting changes in an Angular directive

Initially, I created a directive that receives an object via bindToController for editing. Everything worked well until I needed to cancel an edit. To undo the changes, I had to create a duplicate of the original object, make changes to it, and then either ...

What is the best way to retrieve specific feature properties in Open Layers 3 on-the-fly?

Within my map, I have two types: Point and Polygon, each with unique properties such as id, door number, and name. I have generated a list of features as follows: var features = new ol.format.GeoJSON().readFeatures(geojsonObject, { featureProjection: & ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...