user1486133 user1486133 - 1 year ago 65
Javascript Question

Using a function on data output in a table with Angular repeater

I'm fairly new to writing decent JS and totally new to Angular.

I'm trying out building a very small app that takes data from an external JSON, and outputs it into a table. I've done that part and now I want to play around with manipulating some of the data.

I output my data into a table using Angular


<tr ng-repeat="pattern in pattern">
<td>{{ pattern.brand }}</td>
<td>{{ }}</td>
<td>{{ pattern.size }}</td>
<td>{{ pattern.quantity}}</td>
<td>{{ pattern.fabricType }}</td>

This all works just fine (see this codepen).

Now I want to start manipulating the data by creating some custom functions. I read a tutorial that had a short function that concatenated data from
fields into
and output them in the table. The function looked like this:

fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;


And it was called using
in the HTML. I want to do something similar. If my
data =
I actually want to output it as
in the table.

I wrote this function:

// Function to name the quantity field correctly
function quantityLabel() {
if ($scope.pattern.quantity == -1){
return 'Unlimited';
}else {
return quantity;

But I can't work out a succinct way to write a function like this and call it in the template, like in the tutorial.

Here's my broken codepen. What am I doing wrong?

Answer Source

Try this in your controller:

$scope.quantityLabel = function (quantity) {
    return quantity === -1 ? 'Unlimited' : quantity;

And then in your template call it like this:



Just to clarify a bit on what is going on here, you want to attach a function to the scope that takes the quantity value, modifies it and returns the value you want. As you can see the scope function takes a parameter "quantity" and returns a string "infinity" if the value is -1. If not, it returns the original quantity. In the template, we are calling this function passing $scope.pattern.quantity.

Each digest cycle, angular will pass $scope.pattern.quantity into the function and display it's return value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download