Manish Joshi
Manish Joshi

Reputation: 93

How to restrict duplicate entry in custom directive Angularjs

Below is my custom directive and it will appear when our view will render.

  (function() {
    'use strict';

    function autoComplete(Configuration) {
            //link function will execute when this directive will render with view.
      function linkFn(scope, element) {
        //in scope.data I will get all my data from the controller but need to parse only unique data here
        //in scope.data I want only unique entries
        console.log(scope.data);
        var config = {
          source: function(request, response) {
            var results = $.ui.autocomplete.filter(scope.data || [], request.term);
            response(results.slice(0, Configuration.MAX_AUTOCOMPLETE_RESULT));
          }
        };
        //all set let's initialise the auto complete of jquery.
        element.autocomplete(config);
      }

      //our directive definition object.
      return {
        restrict: 'A',
        // Isolated scope for our directive.
        scope: {
          data: '='
        },
        link: linkFn
      };
    }

    var app = angular.module('app'),
      requires = [
        'Configuration',
        autoComplete
      ];
    app.directive('autoComplete', requires);
  }());

Here is directive I will get data from the controller and I want to parse unique data from scope.data.

Upvotes: 0

Views: 117

Answers (1)

sisyphus
sisyphus

Reputation: 462

Not sure if this is what you are looking for but duplicates in a javascript array can be removed using Array.filter.

var arr =  ["abc","xyz","abc","pqr"]
console.log('duplicate array : ' + arr)

var unique_arr = arr.filter(function(element, index, array) {
    return index == array.indexOf(element);
})

console.log('unique arr ' + unique_arr);

For further reading, check here

Upvotes: 1

Related Questions