I am trying to get an Angular controller to consume some JSON, as below and make a call to the "userService" which has a function called "calculateAge". This function will do a diff between the date provided, and the individual JSON objects dateOfBirth to return an age.
I know this might not be the best way of achieving this, this is just an illustrative example.
What I am having difficulties with is calling the userService.calculateAge and getting it to populate an "age" value on each JSON object. I ideally want the value the function returns each time to do this, so that I can better understand how functions can be called within Angular.
My gut instinct is that I am nearly there, and perhaps need to use a for-each loop or similar, however my Angular skills consist of about 2 days learning!
Sample data:
[{
"firstName":"Bob", "lastName":"Smith", "dateOfBirth":"14-12-1988",
"email":"BSmith", "mobileNumber":null, "landLineNumber":null,
"isAdmin":false, "isModerator":false, "isEnabled":false, "isActivated":false
}, {
"firstName":"Jo", "lastName":"Smith", "dateOfBirth":"15-03-1990",
"email":"Smithy", "mobileNumber":null, "landLineNumber":null,
"isAdmin":false, "isModerator":false, "isEnabled":false, "isActivated":false
}]
My AngularJS controller and service
angular.module("UserApp", [])
.service('userService', function () {
return {
calculateAge: function (dateOfBirth) {
return "23"; //dummy age value here
}
};
})
.controller("listUsersController", ['$scope', '$http', 'userService', function ($scope, $http, userService) {
$http.get("/user/")
.success(function (data, status, headers, config) {
$scope.users = data;
var age = userService.calculateAge($scope.users.dateOfBirth);
$scope.users.age = age;
})
.error(function (data, status, headers, config) {
// log error
});
}] ...