AngularJS Example: Default filter

by Ztyx

HTML

<div ng-app="telavox.test">
    <div>
        <div class="controller" data-ng-controller="MyListLengthAddedController">
            {{empty | fallback:'Not set.'}}<br/>
            {{undeffed | fallback:'Not set.'}}<br/>
        </div>
    </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<style>

JavaScript

angular.module('telavox.test', [])
.controller('MyListLengthAddedController', function($scope) {
    $scope.empty = "";
    $scope.undeffed = undefined;
    
})
.filter('fallback', function() {
    return function val(el, fallback) {
        if (!String.prototype.trim) {
            String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
        }
        
        if (el && el.trim() != "") {
            return el;
        } else {
            return fallback;
        }
    }
});