javascript AngularJS 在模板上使用正则表达式替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28874898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:41:55  来源:igfitidea点击:

AngularJS replace using regex on template

javascriptregexangularjsreplace

提问by Alex Arvanitidis

I have the following markup that shows a value from ng-model.

我有以下标记显示来自 ng-model 的值。

<a ng-click="downloadDocument()">{{document.content.replace(/\d+\_/,"")}}</a>

Before each document.content I add a number and an underscore, smth like "12122141_document.txt". I want to replace this part by using this regex /\d+_/

在每个 document.content 之前,我添加一个数字和一个下划线,例如“12122141_document.txt”。我想用这个正则表达式替换这部分 /\d+_/

This throws an error on angularJS, although {{ document.replace(" ","") }} works.

这会在 angularJS 上引发错误,尽管 {{ document.replace(" ","") }} 有效。

Is the only way to solve this a directive or am I doing something wrong?

解决这个问题的唯一方法是指令还是我做错了什么?

Plunker: http://embed.plnkr.co/sh54XZwSIlYnmvY0eTIt/preview

Plunker:http://embed.plnkr.co/sh54XZwSIlYnmvY0eTIt/preview

Cheers,

干杯,

Alex

亚历克斯

采纳答案by lin

I modified your Plunker-Demoand it works pretty fine.

我修改了你的Plunker-Demo,效果很好。

Hint: Don't use $scopenamespaces like "document". Its reserved/used by the client.

提示:不要使用$scope像“document”这样的命名空间。它由客户端保留/使用。

var app = angular.module('plunker', []);

Controller

控制器

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.fileName = {
    content : function(){
      return '1233_test.txt'.replace(/\d+\_/,"");
    }
  }

  $scope.mpla = function () {
    console.log('clicked');
  }

});

View

看法

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.14/angular.js" data-semver="1.3.14"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p> 
  <a ng-click="mpla()" ng-bind="fileName.content()"></a>
</body>

</html>