用于短语内单词的角度过滤器

时间:2016-10-16 04:10:16

标签: javascript angularjs angularjs-filter

我正在构建一个AngularJS应用。我有这个数组:

<li ng-repeat="product in products | filter : { name : word }">
  {{ $product.name }}
</li>

然后我用ng-repeat显示它。

$scope.word = 'ca';

我想添加一个过滤器来搜索短语中每个单词的开头,所以如果我这样做:

$scope.products = [
  {name: 'cake (just it!)'},
  {name: 'orange cake'}
];

它将返回以下数组:

$(document).ready(function(){
    // canvas related variables
    canvas = document.getElementById("mm-canvas");
    ctx = canvas.getContext("2d");
    imageObj = new Image();
    maxFontSize = 60;

    MAX_WIDTH = $('#meme-canvas').innerWidth()-20;
    MAX_HEIGHT = MAX_WIDTH;

    imageObj.onload = function(){
        width = imageObj.width;
        height = imageObj.height;

        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        }
        else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }
        canvas.width = width;
        canvas.height = height;
        draw();
    };
    imageObj.src = $(canvas).data('image');

    $(document).on('keyup', '.mm-text', function(){
        draw();
    });

    $('#add-textbox').click(function(){
        var that = $(this);
        var makeid = makeId();
        that.parent().before('<div class="form-group mb-form-group"><input type="text" data-position="'+makeid+'" name="title" placeholder="More Text" class="form-control mm-text pull-left"><div class="mm-spectrum pull-right"><input type="text" value="#fff" class="font" class="form-control"><input type="text" value="#000" class="stroke" class="form-control"></div><div class="clearfix"></div></div>');
        $('.resizable:last-child').before('<div id="'+makeid+'" style="position:absolute; top:'+((canvas.height/2)-50)+'px; width:100%; height:100px; opacity:0.4" class="resizable"></div>');

        $('input[data-position="'+makeid+'"]').next().find('.font').spectrum({
            clickoutFiresChange: true,
        });
        $('input[data-position="'+makeid+'"]').next().find('.stroke').spectrum({
            clickoutFiresChange: true,
        });

        $("#"+makeid).resizable({
          containment: ".mm-contain",
          stop: function(){ draw(); }
        }).draggable({
            containment: '.mm-contain',
            stop: function(){ draw(); }
        });

    });

    $('.mm-contain').hover(function(){
        $('.resizable').toggleClass('ui-state-active');
    });

    $( ".resizable" ).resizable({
      containment: ".mm-contain",
      stop: function(){ draw(); }
    }).draggable({
        containment: '.mm-contain',
        stop: function(){ draw(); }
    });
    $(".font").spectrum({
        clickoutFiresChange: true,
    });
    $(".stroke").spectrum({
        clickoutFiresChange: true,
    });

    $(document).on('change', '.font, .stroke', draw);

});
function makeId(){
    var text = "";
    var possible = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// clear the canvas & redraw all texts
function draw() {
    ctx.save();
    ctx.textAlign = "center";
    ctx.lineWidth = 1;
    ctx.shadowBlur = 1;
    ctx.clearRect(0, 0, width, height);
    ctx.drawImage(imageObj, 0, 0, width, height);

    $('.mm-text').each(function(index){
        var that = $(this);
        var text = that.val().trim();

        var dataPos = that.attr('data-position');

        var textboxWidth = $('#'+dataPos).innerWidth();
        that.attr('data-fontsize', maxFontSize);
        var textFont = that.attr('data-fontsize');

        ctx.font= textFont+"px impact";

        var linest = fragmentText(text, textboxWidth-textFont);

        if(linest.length == 1){
            //maxFontSize = 60;
            that.attr('data-fontsize', maxFontSize);
        }
        if(linest.length == 2){
            //maxFontSize = 50;
            that.attr('data-fontsize', 50);
        }
        if(linest.length == 3){
            //maxFontSize = 40;
            that.attr('data-fontsize', 40);
        }
        if(linest.length >= 4){
            //maxFontSize = 30;
            that.attr('data-fontsize', 30);
        }
        textFont = that.attr('data-fontsize');
        ctx.font= textFont+"px impact";
        ctx.fillStyle = that.next().find('.font').val()
        ctx.shadowColor = that.next().find('.stroke').val();
        ctx.strokeStyle = that.next().find('.stroke').val();

        var lines = fragmentText(text, textboxWidth-textFont);
        $('#'+dataPos).css('height', parseInt(lines.length*textFont)+'px');
        lines.forEach(function(line, i) {
            ctx.fillText(line.toUpperCase(), parseInt($('#'+dataPos).position().left + (textboxWidth/2)), parseInt($('#'+dataPos).position().top + (i + 1) * textFont));
            ctx.strokeText(line.toUpperCase(), parseInt($('#'+dataPos).position().left + (textboxWidth/2)), parseInt($('#'+dataPos).position().top + (i + 1) * textFont));
        });
    });
}

function fragmentText(text, maxWidth) {
    var words = text.toString().split(' '),
        lines = [],
        line = "";
    if (ctx.measureText(text).width < maxWidth) {
        return [text];
    }
    while (words.length > 0) {
        while (ctx.measureText(words[0]).width >= maxWidth) {
            var tmp = words[0];
            words[0] = tmp.slice(0, -1);
            if (words.length > 1) {
                words[1] = tmp.slice(-1) + words[1];
            } else {
                words.push(tmp.slice(-1));
            }
        }
        if (ctx.measureText(line + words[0]).width < maxWidth) {
            line += words.shift() + " ";
        } else {
            lines.push(line);
            line = "";
        }
        if (words.length === 0) {
            lines.push(line);
        }
    }
    return lines;
}

function saveCanvas()
{
    temp_width = MAX_WIDTH;
    temp_height = MAX_HEIGHT;
    MAX_WIDTH = 500;
    MAX_HEIGHT = MAX_WIDTH;
    draw();
    var canvas = document.getElementById("mm-canvas");
    ctx.font = '12px Arial';
    ctx.fillStyle = '#fff';
    ctx.shadowBlur = 2;
    ctx.shadowColor = '#000';
    ctx.textAlign = "left";
    ctx.fillText(waterMarkText, 3, canvas.height - 3);
    var theimage=canvas.toDataURL("image/png");
    MAX_WIDTH = temp_width;
    MAX_HEIGHT = temp_height;
    draw();
    $.post(rootURL+'/canvas',
        { image: theimage, _token: $('meta[name="_token"]').attr('content') },
        function(data){
            data = jQuery.parseJSON(data);
            if(data.status == 'success')
            {
                window.location.href = rootURL+'/canvas?id='+data.slug;
            }
        }
    );
}

function publishCanvas()
{
    MAX_WIDTH = 500;
    MAX_HEIGHT = MAX_WIDTH;
    draw();
    var canvas = document.getElementById("mm-canvas");
    var theimage=canvas.toDataURL("image/png");
    var ctitle = '';

    var form = $('<form action="'+rootURL+'/create?publish=yes" method="post">' +
    '<input type="hidden" name="canvas" value="'+theimage+'" />' +
    '<input type="hidden" name="ctitle" value="'+ctitle+'" />' +
    '<input type="hidden" name="_token" value="'+$('meta[name="_token"]').attr('content')+'" />' +
    '</form>');
    $('body').append(form);
    $(form).submit();
}

1 个答案:

答案 0 :(得分:1)

您可以使用下面提到的自定义过滤器

&#13;
&#13;
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.products = [{
      name: 'cake (just it!)'
    }, {
      name: 'orange cake'
    }, {
      name: 'cheesecake'
    }, {
      name: 'cheese'
    }, {
      name: 'cheeseca ca'
    }];

  }
]);

app.filter("nameFilter", function() {

  return function(names, contains) {
    return names.filter(function(obj) {
      var expString = '(\\w*\\s|^)' + contains + '';
      var exp = new RegExp(expString, "g");

      if (exp.test(obj.name))
        return name;
    });
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <ul>
      <li ng-repeat="product in products | nameFilter : 'ca' ">
        {{product.name}}
      </li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;