Reputation: 357
I'm trying to do a simple function in my angular js trial.
I cannot get the method call to work, it only displays it all as text. I cannot figure out what I have done wrong in such a small thing.
This is my entire code and below is a screenshot of the result.
The html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app.js"></script>
<body ng-app="beerApp">
<div ng-controller="contentC">
<div>
<ul>
<select ng-model="currentItem" ng-options="item.name for item in items"></select>
</ul>
</div>
<div>
<p>{{ currentItem.name }}</p>
<p>{{ currentItem.country }}</p>
<p>{{ average(currentItem.ratings) }}</p>
<p ng-repeat="rating in currentItem.ratings">{{ rating.rating }}</p>
</div>
</div>
The js
var app = angular.module('beerApp', []);
app.controller('contentC', function($scope) {
$scope.items = [
{name:'Rignes',country:'Norway', ratings:[
{"rating":3}, {"rating":3}, {"rating":2}]},
{name:'Pripps',country:'Sweden', ratings:[
{"rating":2}, {"rating":3}, {"rating":5}]},
{name:'Tuborg',country:'Denmark', ratings:[
{"rating":5}, {"rating":4}, {"rating":3}]}
];
$scope.currentItem = {name:'Nothing'};
$scope.average = function (data) {
console.log("called")
var sum = 0;
for(var i = 0; i < data.lenght; i++){
sum += parseInt(data[i].rating);
}
var avg = sum/data.lenght;
return avg;
};
});
Corrected js code
$scope.average = function (data) {
var sum = 0;
var ratings = 0;
try {
for (var d in data){
sum += parseInt(data[d].rating);
ratings++;
}
} catch (error) {
sum = 0;
}
var avg = sum/ratings;
return avg;
};
Upvotes: 0
Views: 203
Reputation: 4286
Change
<p>{{average()}}</p>
For
<p>{{average(items)}}</p>
Also, try checking your console (ctrl+shift+i)
Upvotes: 0
Reputation: 4841
The average
function is throwing an error so Angular is leaving the binding as-is because there's no sensible value to bind to it.
There are a couple of errors in your code:
length
is spelt incorrectlydata.ratings.length
rather than data.length
currentItem
does not have a ratings property. Working demo http://codepen.io/anon/pen/reqbZG
var app = angular.module('beerApp', []);
app.controller('contentC', function($scope) {
$scope.items = [
{name:'Rignes',country:'Norway', ratings:[
{"rating":3}, {"rating":3}, {"rating":2}]},
{name:'Pripps',country:'Sweden', ratings:[
{"rating":2}, {"rating":3}, {"rating":5}]},
{name:'Tuborg',country:'Denmark', ratings:[
{"rating":5}, {"rating":4}, {"rating":3}]}
];
$scope.currentItem = {name:'Nothing', ratings: []};
$scope.average = function (data) {
var sum = 0;
for(var i = 0; i < data.ratings.length; i++){
sum += parseInt(data.ratings[i].rating);
}
var avg = sum/data.ratings.length;
return avg;
};
});
And the slightly updated HTML (average method call):
<!-- snip -->
<p>{{ currentItem.name }}</p>
<p>{{ currentItem.country }}</p>
<p>{{average(currentItem)}}</p>
<p ng-repeat="rating in currentItem.ratings">{{ rating.rating }</p>
<!-- snip -->
Upvotes: 1