1

I have this code:

    <pre>totalItems: {{vm.pagination.totalItems}}</pre>
    <pre>items-per-page: {{vm.pagination.itemsPerPage}}</pre>
    <pre>Total: Math.ceil({{vm.pagination.totalItems / vm.pagination.itemsPerPage}})</pre>

Output:

enter image description here

I'm using Math.ceil() so the answer should be 11 but I'm not getting the correct answer as below:

enter image description here

How can I calculate angular value in braces? Please help and thanks in advance.

2
  • 2
    You can't use Math in the view, unless you define it as part of your scope ($scope.Math = Math //in your controller). And in that case it would be {{ Math.ceil(whatever number) }} Commented Jan 17, 2017 at 20:52
  • 1
    To support @yBrodsky answer, here is the fiddle jsfiddle.net/U3pVM/29519 Commented Jan 17, 2017 at 21:45

3 Answers 3

1

The best way is to create a scoped function:

<pre>Total: {{calculateTotal(vm.pagination.totalItems, vm.pagination.itemsPerPage)}}</pre>

Then add the function to the scope:

$scope.calculateTotal = function(totalItems, itemsPerPage) {
  return Math.ceil(totalItems/itemsPerPage);
};
Sign up to request clarification or add additional context in comments.

Comments

1

angular.module('myapp', [])
  .controller('foo', function($scope) {

var vm = this;

vm.w = {
pagination: {
	totalItems: 258,
	itemsPerPage: 25
}
}

init();

return vm.w;

function init() {
	vm.w.pagination.calculation = Math.ceil(vm.w.pagination.totalItems / vm.w.pagination.itemsPerPage)
}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myapp">
<div ng-controller="foo as vm">

	<pre>totalItems: {{vm.pagination.totalItems}}</pre>
    <pre>items-per-page: {{vm.pagination.itemsPerPage}}</pre>
    <pre>Total: {{vm.pagination.calculation}}</pre>


</body>

Comments

1

If you need to use Math in the template, you will need to expose it. So in your controller you would set

vm.Math = Math;

and you would then use it in the template like so:

<pre>Total: {{ vm.Math.ceil(vm.pagination.totalItems / vm.pagination.itemsPerPage }})</pre>

However, rather than doing the calculation in the template you would be better off exposing a function that calculates the value in your controller:

vm.getTotalPageCount = function() {
    return Math.ceil(vm.pagination.totalItems / vm.pagination.itemsPerPage);
};

And use it in your template:

<pre>Total: {{ vm.getTotalPageCount() }})</pre>

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.