0

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?

1

3 Answers 3

5

from the AngularJS limitTo docs you could do:

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

Or see this plunkr for more options.

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

Comments

0
    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>

Comments

0

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

4 Comments

I've gone ahead and used {{number |limitTo : -4 : number.length}} however it's still not working and only displaying the full number.. is there something I am missing?
Edit: I am using angularjs 1.0.7 not 1.4.2.
But in your post you given 1.4.2
I have added EDIT CODE for 1.0.7.Please check it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.