angluarjs实现过滤并替换关键字

html样式

1 <body ng-app="myapp" ng-controller="myCtrl">
2     <input type="text" ng-model="keytext">
3     <p>{{ keytext|wordFilter:"#" }}</p>
4     <p>{{ keytext|wordFilter2}}</p>
5 </body>

//第一种,替换关键词过滤器 

1 var myapp=angular.module("myapp",[]);
2         /*第一种,替换关键词自定义过滤器*/
3         myapp.filter("wordFilter",function () {
4             return function (msg,flag) {
5                 /*替换关键词*/
6                 return msg.replace(/枪|子弹/g,flag);
7             }
8         })

//第二种替换关键字

 1 /第二种方法,将每个字关键字都变为固定符号
 2         myapp.filter("wordFilter2",function(){
 3             return function(msg){
 4                 return msg.replace(/子弹|枪/g,function(word){
 5                     //-----------传入word吐出content
 6                     var content='';
 7                     //有几个字,写出几个字
 8                     for(var i= 0;i<word.length;i++){
 9                         content+="*";
10                     }
11                     return content;
12                 });
13             };
14         });

//控制器

 1 myapp.controller("myCtrl",function ($scope) {

2   $scope.keytext="";

3 }) 

 最后的效果图:

原文地址:https://www.cnblogs.com/xjean/p/7550066.html