Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 替换文本的Angularjs指令_Javascript_Angularjs - Fatal编程技术网

Javascript 替换文本的Angularjs指令

Javascript 替换文本的Angularjs指令,javascript,angularjs,Javascript,Angularjs,我如何在angularjs中创建一个指令,例如采用以下元素: <div>Example text http://example.com</div> 示例文本http://example.com 把它转换成这个 <div>Example text <a href="http://example.com">http://example.com</a></div> 示例文本 我已经编写了在函数中自动链接文本并返回html的

我如何在angularjs中创建一个指令,例如采用以下元素:

<div>Example text http://example.com</div>
示例文本http://example.com
把它转换成这个

<div>Example text <a href="http://example.com">http://example.com</a></div>
示例文本
我已经编写了在函数中自动链接文本并返回html的功能(让我们称该函数为“autoLink”),但我的指令还不完善

我还想向元素添加一个属性,以便将对象传递到指令中。e、 g

<div linkprops="link.props" >Example text http://example.com</div>
示例文本http://example.com

其中link.props是类似于{a:'bla-bla',b:'waa-waa'}的对象,它将作为第二个参数传递给autoLink函数(第一个参数是文本)。

我将在指令上分析link函数中的文本:

directive("myDirective", function(){

  return {
        restrict: "A",
        link: function(scope, element, attrs){
          // use the 'element' to manipulate it's contents...
        }
      }
  });
有两种方法:

指示
app.directive('parseUrl',函数(){
var urlPattern=/(http | ftp | https):\/\/[\w-]+(\.[\w-]+)+([\w,@?^=%&;:\/~+-]*[\w@?^=%&;/~+-])/gi;
返回{
限制:“A”,
要求:'ngModel',
替换:正确,
范围:{
道具:'=parseUrl',
ngModel:'=ngModel'
},
链接:函数编译(范围、元素、属性、控制器){
范围:$watch('ngModel',函数(值){
var html=value.replace(urlPattern.)+“|”+scope.props.otherProp;
html(html);
});
}
};
});
HTML:

滤器
app.filter('parseUrlFilter',函数(){
var urlPattern=/(http | ftp | https):\/\/[\w-]+(\.[\w-]+)+([\w,@?^=%&;:\/~+-]*[\w@?^=%&;/~+-])/gi;
返回函数(文本、目标、其他属性){
返回文本。替换(urlPattern.)+“|”+otherProp;
};
});
HTML:

注意:
'otherProperty'
只是一个例子,以防您想将更多属性传递到过滤器中


更新:改进了替换算法。

我想要一个可以交换文本的暂停按钮。我是这样做的:

在CSS中:

.playpause.paused .pause, .playpause .play { display:none; }
.playpause.paused .play { display:inline; }
在模板中:

<button class="playpause" ng-class="{paused:paused}" ng-click="paused = !paused">
  <span class="play">play</span><span class="pause">pause</span>
</button>

暂停播放

要回答此问题的前半部分,在没有额外属性要求的情况下,可以使用Angular的linky筛选器:

如果存在多个链接,则顶部投票的答案不起作用。Linky已经为我们完成了90%的工作,唯一的问题是它清理了html,从而删除了html/换行符。我的解决方案是只编辑linky过滤器(下面是Angular 1.2.19),不清理输入

app.filter('linkyUnsanitized', ['$sanitize', function($sanitize) {
  var LINKY_URL_REGEXP =
        /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/,
      MAILTO_REGEXP = /^mailto:/;

  return function(text, target) {
    if (!text) return text;
    var match;
    var raw = text;
    var html = [];
    var url;
    var i;
    while ((match = raw.match(LINKY_URL_REGEXP))) {
      // We can not end in these as they are sometimes found at the end of the sentence
      url = match[0];
      // if we did not match ftp/http/mailto then assume mailto
      if (match[2] == match[3]) url = 'mailto:' + url;
      i = match.index;
      addText(raw.substr(0, i));
      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
      raw = raw.substring(i + match[0].length);
    }
    addText(raw);
    return html.join('');

    function addText(text) {
      if (!text) {
        return;
      }
      html.push(text);
    }

    function addLink(url, text) {
      html.push('<a ');
      if (angular.isDefined(target)) {
        html.push('target="');
        html.push(target);
        html.push('" ');
      }
      html.push('href="');
      html.push(url);
      html.push('">');
      addText(text);
      html.push('</a>');
    }
  };
}]);
app.filter('linkyunsicanited',['$sanitize',函数($sanitize){
变量LINKY\u URL\u REGEXP=
/((ftp | https?):\/\/|(mailto:)?[A-Za-z0-9.\%+-]+@)\S*[^\S;,(){}]/,,
MAILTO_REGEXP=/^MAILTO:/;
返回函数(文本、目标){
如果(!text)返回文本;
var匹配;
var raw=文本;
var html=[];
var-url;
var i;
而((match=raw.match(LINKY\u URL\u REGEXP))){
//我们不能以这些结尾,因为它们有时出现在句子的末尾
url=匹配[0];
//如果我们不匹配ftp/http/mailto,则假定为mailto
如果(匹配[2]==match[3])url='mailto:'+url;
i=匹配索引;
addText(原始substr(0,i));
addLink(url,匹配[0]。替换(MAILTO_REGEXP.);
raw=raw.substring(i+match[0]。长度);
}
添加文本(原始);
返回html.join(“”);
函数addText(文本){
如果(!text){
返回;
}
html.push(文本);
}
函数addLink(url、文本){
html.push(“”);
}
};
}]);

受@Neal的启发,我从较新的Angular 1.5.8版中制作了这个“无消毒”过滤器。它还可以识别没有ftp | http(s)但以www开头的地址。这意味着
https://google.com
www.google.com
将被链接

angular.module('filter.parselinks',[])

.filter('parseLinks', ParseLinks);

function ParseLinks() {
  var LINKY_URL_REGEXP =
        /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
      MAILTO_REGEXP = /^mailto:/i;

  var isDefined = angular.isDefined;
  var isFunction = angular.isFunction;
  var isObject = angular.isObject;
  var isString = angular.isString;

  return function(text, target, attributes) {
    if (text == null || text === '') return text;
    if (typeof text !== 'string') return text;

    var attributesFn =
      isFunction(attributes) ? attributes :
      isObject(attributes) ? function getAttributesObject() {return attributes;} :
      function getEmptyAttributesObject() {return {};};

    var match;
    var raw = text;
    var html = [];
    var url;
    var i;
    while ((match = raw.match(LINKY_URL_REGEXP))) {
      // We can not end in these as they are sometimes found at the end of the sentence
      url = match[0];
      // if we did not match ftp/http/www/mailto then assume mailto
      if (!match[2] && !match[4]) {
        url = (match[3] ? 'http://' : 'mailto:') + url;
      }
      i = match.index;
      addText(raw.substr(0, i));
      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
      raw = raw.substring(i + match[0].length);
    }
    addText(raw);
    return html.join('');

    function addText(text) {
      if (!text) {
        return;
      }
      html.push(text);
    }

    function addLink(url, text) {
      var key, linkAttributes = attributesFn(url);
      html.push('<a ');

      for (key in linkAttributes) {
        html.push(key + '="' + linkAttributes[key] + '" ');
      }

      if (isDefined(target) && !('target' in linkAttributes)) {
        html.push('target="',
                  target,
                  '" ');
      }
      html.push('href="',
                url.replace(/"/g, '&quot;'),
                '">');
      addText(text);
      html.push('</a>');
    }
  };
}
angular.module('filter.parselinks',[])
.filter('parseLinks',parseLinks);
函数ParseLinks(){
变量LINKY\u URL\u REGEXP=
/((ftp | https?):\/\/|(www\)|(mailto:)?[A-Za-z0-9.\u%+-]+@][S*[^\S;,(){}”\u201d\u2019]/i,
MAILTO_REGEXP=/^MAILTO:/i;
var isDefined=angular.isDefined;
var isFunction=angular.isFunction;
var isObject=角度isObject;
var isString=angular.isString;
返回函数(文本、目标、属性){
如果(text==null | | text==='')返回文本;
if(typeof text!=“string”)返回文本;
var属性fn=
isFunction(属性)?属性:
isObject(属性)?函数GetAttributeObject(){返回属性;}:
函数getEmptyAttributesObject(){return{};};
var匹配;
var raw=文本;
var html=[];
var-url;
var i;
而((match=raw.match(LINKY\u URL\u REGEXP))){
//我们不能以这些结尾,因为它们有时出现在句子的末尾
url=匹配[0];
//如果我们不匹配ftp/http/www/mailto,则假定为mailto
如果(!match[2]&&!match[4]){
url=(匹配[3]?'http://':'mailto:')+url;
}
i=匹配索引;
addText(原始substr(0,i));
addLink(url,匹配[0]。替换(MAILTO_REGEXP.);
raw=raw.substring(i+match[0]。长度);
}
添加文本(原始);
返回html.join(“”);
函数addText(文本){
如果(!text){
返回;
}
html.push(文本);
}
函数addLink(url、文本){
var键,linkAttributes=attributesFn(url);
html.push(“”);
}
};
}

我已经试过了,但是当我使用element.text('bla')时,它会将html显示为text。你可以分享你的JSFIDdle吗?我刚刚更新了这个问题,因为我意识到我需要更多的功能。你有什么理由需要一个特定于此的指令吗?ngHref没有选项吗?(它接受角度表达式)因此,您希望在元素的文本中搜索URL,并从中创建链接
.playpause.paused .pause, .playpause .play { display:none; }
.playpause.paused .play { display:inline; }
<button class="playpause" ng-class="{paused:paused}" ng-click="paused = !paused">
  <span class="play">play</span><span class="pause">pause</span>
</button>
app.filter('linkyUnsanitized', ['$sanitize', function($sanitize) {
  var LINKY_URL_REGEXP =
        /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/,
      MAILTO_REGEXP = /^mailto:/;

  return function(text, target) {
    if (!text) return text;
    var match;
    var raw = text;
    var html = [];
    var url;
    var i;
    while ((match = raw.match(LINKY_URL_REGEXP))) {
      // We can not end in these as they are sometimes found at the end of the sentence
      url = match[0];
      // if we did not match ftp/http/mailto then assume mailto
      if (match[2] == match[3]) url = 'mailto:' + url;
      i = match.index;
      addText(raw.substr(0, i));
      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
      raw = raw.substring(i + match[0].length);
    }
    addText(raw);
    return html.join('');

    function addText(text) {
      if (!text) {
        return;
      }
      html.push(text);
    }

    function addLink(url, text) {
      html.push('<a ');
      if (angular.isDefined(target)) {
        html.push('target="');
        html.push(target);
        html.push('" ');
      }
      html.push('href="');
      html.push(url);
      html.push('">');
      addText(text);
      html.push('</a>');
    }
  };
}]);
angular.module('filter.parselinks',[])

.filter('parseLinks', ParseLinks);

function ParseLinks() {
  var LINKY_URL_REGEXP =
        /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
      MAILTO_REGEXP = /^mailto:/i;

  var isDefined = angular.isDefined;
  var isFunction = angular.isFunction;
  var isObject = angular.isObject;
  var isString = angular.isString;

  return function(text, target, attributes) {
    if (text == null || text === '') return text;
    if (typeof text !== 'string') return text;

    var attributesFn =
      isFunction(attributes) ? attributes :
      isObject(attributes) ? function getAttributesObject() {return attributes;} :
      function getEmptyAttributesObject() {return {};};

    var match;
    var raw = text;
    var html = [];
    var url;
    var i;
    while ((match = raw.match(LINKY_URL_REGEXP))) {
      // We can not end in these as they are sometimes found at the end of the sentence
      url = match[0];
      // if we did not match ftp/http/www/mailto then assume mailto
      if (!match[2] && !match[4]) {
        url = (match[3] ? 'http://' : 'mailto:') + url;
      }
      i = match.index;
      addText(raw.substr(0, i));
      addLink(url, match[0].replace(MAILTO_REGEXP, ''));
      raw = raw.substring(i + match[0].length);
    }
    addText(raw);
    return html.join('');

    function addText(text) {
      if (!text) {
        return;
      }
      html.push(text);
    }

    function addLink(url, text) {
      var key, linkAttributes = attributesFn(url);
      html.push('<a ');

      for (key in linkAttributes) {
        html.push(key + '="' + linkAttributes[key] + '" ');
      }

      if (isDefined(target) && !('target' in linkAttributes)) {
        html.push('target="',
                  target,
                  '" ');
      }
      html.push('href="',
                url.replace(/"/g, '&quot;'),
                '">');
      addText(text);
      html.push('</a>');
    }
  };
}