Zerok
Zerok

Reputation: 1503

Filter issue in Angular

I'm trying to use a filter that reverses a string, this is my code:

app.filter("revertir", function(){

    return function(input){
        var u = input.length-1;

        console.log("ENTRA: "+input);
        for(var i=0;i<input.length/2;i++){
            var temp = input[i];
            input[i] = input[u];
            input[u] = temp;
            u--;
        }
        return input;
    };
});

I inject this filter into my controller, and it's thrown properly, but I'm not getting the text reversed; it shows up exactly as the input string.

Where's the problem? This exact script for reversing works perfect in a Java test program.

Upvotes: 0

Views: 53

Answers (2)

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

Another way to implement it :

var app = angular.module("MyApp", []);

app.filter("reverse", function() {
  return function(input) {
    return ( (input || '').split('').reverse().join(''));
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
  
    write here: <input ng-model="strIn" ng-init="strIn='Hello Wordl!'" />
    <p>output reversed : {{ strIn | reverse }}</p>
  
</div>

Upvotes: 2

thegio
thegio

Reputation: 1243

pretty common:

var app = angular.module("MyApp", []);

app.filter("reverse", function() {
  return function(input) {
    var result = "";
    input = input || "";
    for (var i=0; i<input.length; i++) {
      result = input.charAt(i) + result;
    }
    return result;
  };
});

Upvotes: 0

Related Questions