sg552
sg552

Reputation: 1543

How to calculated angular variable in braces

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.

Upvotes: 1

Views: 1016

Answers (3)

evsheino
evsheino

Reputation: 2277

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>

Upvotes: 1

lealceldeiro
lealceldeiro

Reputation: 14968

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>

Upvotes: 1

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

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);
};

Upvotes: 1

Related Questions