Corey Ogburn
Corey Ogburn

Reputation: 24717

The Angular way to use a function result in a template?

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

Answers (3)

Dalorzo
Dalorzo

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

Davin Tryon
Davin Tryon

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

aludvigsen
aludvigsen

Reputation: 5981

You can do it like this:

JSFIDDLE

$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

Related Questions