user1486133 user1486133 - 4 months ago 13
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

ng-repeater
:

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


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
firstName
and
lastName
fields into
fullName
and output them in the table. The function looked like this:

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


reference: http://www.tutorialspoint.com/angularjs/angularjs_tables.htm

And it was called using
{{student.fullName()}}
in the HTML. I want to do something similar. If my
quantity
data =
-1
I actually want to output it as
Unlimited
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

Try this in your controller:

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

And then in your template call it like this:

<td>{{quantityLabel(pattern.quantity)}}</td>

EDIT:

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.