如何限制自定义指令Angularjs中的重复条目

时间:2022-09-26 11:22:33

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.

这是指令我将从控制器获取数据,我想解析scope.data中的唯一数据。

1 个解决方案

#1


1  

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

不确定这是否是您正在寻找的,但可以使用Array.filter删除javascript数组中的重复项。

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

如需进一步阅读,请点击此处

#1


1  

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

不确定这是否是您正在寻找的,但可以使用Array.filter删除javascript数组中的重复项。

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

如需进一步阅读,请点击此处