Reputation: 24717
I'm still new to angular and figuring it out as I go with a few examples. What I'm trying to do now is find a proper way to format something. I have a Job object that looks like this:
$scope.Job = {
"JobUID": 100,
"FirstName": "Corey",
"LastName": "Ogburn"
}
And on my page, I want to display it something like this:
<p>Patient Name: {{ Job.LastName + ', ' + Job.FirstName }}</p>
Although this works, I'm hoping there's a way to call a function that prepares the name. For example having a GetFullName()
function on my Job object and then having a template similar to:
<p>Patient Name: {{ Job.GetFullName() }}</p>
This doesn't seem to work. I've read up on custom filters, but I'm not sure if that's the right way to do it. I think I'd have to pass in the entire Job and I'm inclined to find another way to do it before trying that.
How can I use a function to prepare data to be used in a template?
Upvotes: 0
Views: 84
Reputation: 20014
There are "objects" in angular that can help you with the task you mentioned those are "Services" or "Factories". They are not more than Javascript classes(objects) that you can later inject in your controller not much different than what you do with the $scope
.
But in order to simplify the process you can implement a class either directly in your controller or outside of it, doing something like this:
function Job() {
this.JobUID = 100;
this.FirstName = "Corey";
this.LastName= "Ogburn";
}
Job.prototype.GetFullName = function(){
return this.LastName + ',' + this.FirstName;
}
$scope.Job = new Job();
Then on your HTML code:
<p>Patient Name: {{ Job.GetFullName() }}</p>
Upvotes: 1
Reputation: 67296
Try this for a function, it should work:
<p>Patient Name: {{ GetFullName(Job) }}</p>
JS (controller):
$scope.GetFullName = function(job) {
return job.LastName+ ', ' + job.FirstName;
}
Upvotes: 1
Reputation: 5981
You can do it like this:
$scope.Job = {
"JobUID": 100,
"FirstName": "Corey",
"LastName": "Ogburn"
}
$scope.fullname = function() {
return $scope.Job.LastName + ", " + $scope.Job.FirstName;
}
Markup:
<p>Patient Name: {{ fullname() }}</p>
Upvotes: 0