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

时间:2016-10-26 04:53:57

标签: jquery angularjs

以下是我的自定义指令,它将在我们的视图呈现时显示。

  (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);
  }());

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

1 个答案:

答案 0 :(得分:1)

不确定这是否是您要查找的内容,但可以使用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);

如需进一步阅读,请查看here