2

I'm iterating over a list with dates (jobs.submitted):

<div ng-controller="DashboardController as dashboard">


<div ng-repeat="job in dashboard.jobs | filter: {status: 'started'}" class="row"> 
    <div class="col-xs-3">{{job.submitted}}</div>
</div>

Now I want to calculate a duration:

(new Date(job.submitted)) - (new Date(job.completed))

If I put this directly into the expression I get a syntax error (I guess angularJS doesn't understand the Date object).

If I put it into a function, the function in the controller, the function never evaluates:

{{dashboard.getDuration(job)}}

is blank.

What is the best way of tackling this?

4
  • Did you add getDuration as a property on your jobs object? Or is it on your controller? Is dashboard your controller? We need more information. Commented Nov 4, 2015 at 23:34
  • It is really easier to help you if a jsfiddle is provided. Have you tried to put Date into $scope ($scope.Date = Date) or just {{ jobs.getDuration(job) }} (assuming you did this.jobs.getDuration = function ...)? Commented Nov 4, 2015 at 23:35
  • dashboard.jobs seems to be an array, without a function getDuration in there. So, looks like you need to add getDuration into $scope or into this in your controller and then use controller As syntax. Commented Nov 4, 2015 at 23:53
  • things like this should be done in the controller or data service, not in the view Commented Nov 4, 2015 at 23:59

3 Answers 3

2

Try like this

$scope.getDays=function getDays(toDate, fromDate, isNegetiveAllowed) {
    toDate=new Date(toDate);
    fromDate=new Date(fromDate);
    return Math.round((toDate - fromDate) / (1000 * 60 * 60 * 24));
};

HTML

<div ng-repeat="job in dashboard.jobs | filter: {status: 'started'}" class="row"> 
    <div class="col-xs-3">{{ getDays(job.completed,job.submitted) }}</div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't expose the function via this (I'm not using $scope - github.com/johnpapa/angular-styleguide#style-y031). Silly mistake.
0

That should be done in controller not in view. You can try this way:

In view:

{{getJobDiiff(job)}}

In controller:

$scope.getJobDiiff= function(job){
//chage dates in timestamp 
var timestamp1 = new Date(job.submitted).getTime();
var timestamp2 = new Date(job.completed)).getTime();
var diff = timestamp1 - timestamp2;
var newDate = new Date (diff);
return newDate;

}

Comments

0

Here is one way

var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.