ziedTn
ziedTn

Reputation: 262

using angularjs $filter() inside directives

i want to hide some part of the input text value using some filter.

app.directive('limtToDate', ['$filter', function ($filter) {
var dateFormat = "DD/MM/YYYY HH:mm"
return {
    restrict: 'A',
    link: function (scope, ielem, attrs) {
        scope.$watch(attrs.ngModel, function (v) {
            console.log('value changed, new value is: ' + v);
            $filter('limitTo')(ielem.val(), -5);
        });
    }
}}]);

http://jsfiddle.net/PqAhk/2/

well, my input text should just show 12:12 instead of 01/01/1970 12:12. and after editing the time, for example, if user change the time to 12:40 my ng-model has to be like following 1970/01/01 12:40

Upvotes: 5

Views: 5300

Answers (3)

ziedTn
ziedTn

Reputation: 262

First, thank you all, this solution was created by @guru and many thanks to him.

http://plnkr.co/edit/VhsleIWMq8A4rJcVQDaw?p=preview

the solution takes advantage from $formatter and $parser related to the angularjs pipeline rendering.

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

ps : this solution is not compatible with angularjs.2-rc.x

Upvotes: 1

guru
guru

Reputation: 4022

The filter in the link function -> $filter('limitTo')(ielem.val(), -5); filters the array and returns a new array with the filtered values. It has to be assigned back to the scope variable for the changes to get reflected.

Something like below. $scope.filteredValue= $filter('limitTo')(ielem.val(), -5);

Thats intersting. Though formatting can be easy by using $formatter in the ngModelCtl syncing the input data change back to the model can be tricky. You can use the ngModelCtl.$parsers and ngModelCtl.$formatters to set up the format and view value.

Here is a working Solution: http://plnkr.co/edit/1KqLsIwGJjwUIbs0fwmQ?p=preview

Upvotes: 0

user2847643
user2847643

Reputation: 2935

If you don't want your model to change then don't use two way binding:

<div ng-app = "fiddle">
    <div ng-controller="MyCtrl">  
        <table class="table">
            <input type="text" ng-value="fromDate | limitTo:-5" />
        </table>
    </div>
</div>

Better yet why not make from date a real date object:

$scope.fromDate = new Date(); // current date for demonstration, set to real value

And use the date filter:

<input type="text" ng-value="fromDate | date:'HH:mm'" />

Upvotes: 0

Related Questions