6

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

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

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

This throws an error in AngularJS, although {{ document.replace(" ","") }} works.

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

Plunker

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Alex Arvanitidis
  • 4,403
  • 6
  • 26
  • 36
  • Use a $scope with ng-bind and try handle it in your backend. https://docs.angularjs.org/guide/scope & https://docs.angularjs.org/api/ng/directive/ngBind – lin Mar 05 '15 at 09:59
  • It won't work with ng-bind. Plunker: http://embed.plnkr.co/sh54XZwSIlYnmvY0eTIt/preview Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 26-26 [\] in expression [document.content.replace(/\d+\_/,'')] – Alex Arvanitidis Mar 05 '15 at 10:32

1 Answers1

5

I modified your Plunker-Demo and it works pretty fine.

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

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="angular.js@1.3.x" 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>
lin
  • 17,956
  • 4
  • 59
  • 83
  • 2
    Ok, the question was if I could do it by using curly brackets {{ }} on the .html file. Your solution is the next best thing so I added an ng-bind="getFilename()" and created this function to replace the string. – Alex Arvanitidis Mar 05 '15 at 10:54
  • 1
    Using brackets is not the fine way in angular. Code inside brackets is parsed and executed not as $scope. Hope that helped ya out :). Cheers m8. – lin Mar 05 '15 at 11:10