0

I have angular template showing list of items using ng-repeat which does a comparison between properties of the item.
I want the logic to stay in template and display the result right away, but the logic below throw error instead and fail angular to render.
Normal replace with single character works, but not with multiple characters.

<div ng-repeat="item in items">
    <p>{{item.old_name}}</p>
    <input ng-model="item.new_name">
    <span>
        {{item.old_name.replace(/ |_/g, '-') == item.new_name(/ |_/g, '-') ? "same" : "not same"}}
    </span>
</div>

How to fix this?

2
  • 1
    what's the reason for keeping the logic in the template? generally a string comparison such as yours would make a lot of sense in it's own function. Commented Feb 27, 2016 at 3:27
  • The Docs say "No RegExp Creation With Literal Notation: You cannot create regular expressions in an Angular expression." -- AngularJS Developer Guide - Expressions Commented Feb 27, 2016 at 9:47

1 Answer 1

1

I believe your issue is the use of an unescaped | symbol, I'm not sure how you would go about escaping the string within an angular template either - however (imo) the snippet below would be more suitable solution (although does not meet your original question params).

function ctrlr ($scope) {
  $scope.items = [
    { name: 'name one', newname: 'name diff' },
    { name: 'name_two', newname: 'name two' },
    { name: 'name three', newname: 'name three' },
  ]
      
  $scope.compareString = function(str, str2) {
    return str.replace(/ |_/g, '-') === str2.replace(/ |_/g, '-') ? 'same' : 'different'
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-app ng-controller="ctrlr">
  <div ng-repeat="item in items">
    {{ compareString(item.name, item.newname) }}
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Just made the same workaround myself. Well, the snippet doesn't work on me, but the actual app does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.