Reputation: 65
Im trying to make a text formatting Directive in Angular.
In my current application i have many places where i have to present time in HH:MM:SS format, the time in the DB is saved in seconds. So i was thinking that maybe a directive would be the right thing here. For example: everywhere i want to present time in HH:MM:SS i just add the directive "showAsTime" to the element containing the time in seconds.
Q1 What would be the best approach here?
Only part of the code, shown:
<table>
<tr data-ng-repeat="time in timeList">
<td data-show-as-time>{{ time.rowTime }}</td> //time in seconds
<tr>
</table>
The problem is that i dont get the value, the directive is executed first, if i "hardcode" a value say: 900 in place of {{ time.rowTime }} i get the correct presentation "00:15:00".
Q2 In one part of the application i have a model bound to a counter as shown below. Is it possible to make the same Directive work even here?
Only part of the code, shown:
<h1 data-ng-model="timeCounter" data-show-as-time>{{timeCounter}}</h1>
//timeCounter adds 1 to timeCounter every second (with a $interval in the controller).
Time calculations is done as follows,
time.js
app.factory('time',function(){
var timeFactory = {};
timeFactory.timeFromSeconds = function(seconds){
var timeFromSeconds
var minutes = Math.floor(seconds/60);
var hours = Math.floor(seconds/3600);
if(hours > 0) minutes = minutes - hours * 60;
seconds = seconds - hours * 3600 - minutes * 60;
if(hours < 10) hours = "0" + hours;
if(minutes < 10) minutes = "0" + minutes;
if(seconds < 10) seconds = "0" + seconds;
timeFromSeconds = hours +":"+minutes+":" + seconds;
return timeFromSeconds;
}
return timeFactory;
}
Upvotes: 0
Views: 88
Reputation: 9700
Besides the date filter stated in the other answer (https://docs.angularjs.org/api/ng/filter/date), you could also implement a custom filter to further format your model data:
angular.filter('doSomething', function() {
return function(input) {
//do something on your input and return it
}
})
In your html, then, you can call your filter as
{{model|doSomething}}
This is probably the best way to obtain the behavior you want, rather than using a directive.
Upvotes: 0
Reputation: 2667
There is already a date filter in Angular that can do this for you.
Check the link out here: https://docs.angularjs.org/api/ng/filter/date
Upvotes: 2