u111937
u111937

Reputation: 287

Show last few characters when data binding in angularjs

I understand how data binding works in this simple example, however I'm curious on how you could limit the output to display only the last 4 characters of whatever number you put in, instead of the entire number:

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
  </head>
  <body>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="number" placeholder="Enter a long number here">
      <hr>
      <h1>Hello {{number}}!</h1>
    </div>
  </body>
</html>

How would you go about doing this?

Upvotes: 0

Views: 4289

Answers (3)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

you can do it in this way.

<div>
      <label>Name:</label>
      <input type="text" ng-model="number" placeholder="Enter a long number here">
      <hr>
      <h1>Hello {{number |limitTo : -4: number.length}}!</h1>
    </div>

Please refer this more info limitTo

or you can put custom filer in template


EDIT CODE :

With angular 1.0.7, the limitTo filter is work with only Array. For your requirement,you need to implement custom filter. Please check it here for more details.

JS :

angular.module("test",[])
.controller("testCtrl", function ($scope) { 
        $scope.number = ""; 

}).filter("limitToCustom",function(){

    return function(actualData,number){
        console.log(number)
        var arrData = actualData.split("");
        return  actualData.slice(-number);

    }
});

HTML :

<div  ng-controller="testCtrl" class="container">

    <div>
      <label>Name:</label>
      <input type="text" ng-model="number"  placeholder="Enter a long number here">
      <hr>{{number}}
      <h1>Hello {{number |limitToCustom : 4 }}!</h1>
    </div>

</div>

Here is the plunker

Upvotes: 0

Pankaj Ladhar
Pankaj Ladhar

Reputation: 155

    For that you have to write a Custom filter

    **This is the Example:-**

    'use strict';
    var toDoAppFilters = angular.module('toDoAppFilters',[]) ;

    toDoAppFilters.filter('truncate', function() {
        return function(input,length) {
            return (input.length > length ? input.substring(0, length) : input );
        };
    });
  And call like this 
<h1>Hello {{number | truncate:20}}!</h1>

Upvotes: 0

Jax
Jax

Reputation: 1843

from the AngularJS limitTo docs you could do:

<h1>Hello {{number | limitTo: -4}}!</h1>

Or see this plunkr for more options.

Upvotes: 5

Related Questions