Aaron Musktin
Aaron Musktin

Reputation: 307

alter string within angularjs expression

It's possible to make for exmple :

<p>{{data.country}}</p> print out Country:New York, how to alter that to Country:NY ?

Upvotes: 0

Views: 77

Answers (4)

Create a custom filter:

.filter("countryCaps", function(){
  return function(country){
    return "Country: " + country.match(/[A-Z]/g).join("")
  }
})
<p>{{data.country | countryCaps}}</p>

Demo

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You could do it using Regx .match and strings join method.

Markup

 {{data.country.match(pattern).join('')}}

Controller

app.controller('MainCtrl', function($scope, $http) {
$scope.data = {};
  $scope.data.country = 'New York';
  $scope.pattern = /\b(\w)/g;
});

Demo Plunkr

Upvotes: 1

John Munsch
John Munsch

Reputation: 19528

Always remember that what you have inside the {{...}} is an AngularJS expression. That means you can call functions as well.

Just put a function on your scope like this:

$scope.countryTranslator = function (country) {
  if (country === 'New York') {
    return 'NY';
  }
};

and call it like this instead:

{{ countryTranslator(data.country) }}.

Obviously your "translator" should have better code than my example, but you get the idea.

Upvotes: 0

outoftime
outoftime

Reputation: 765

You should use custom filter for this purpose.

But you still have a problem with database of cities full name and they shortcuts, for this purpose, you can use static json file, or use side server service in your choice.

Upvotes: -1

Related Questions