0

consider the following:

 <ul class="contracts">
            <li ng-repeat="contract in contracts" class="thumbnail">
                <h3>ID:{{contract.Id}}</a></h3>                    
                <h4>Owner: {{contract.Person.firstName}} {{contract.Person.lastName}}</h4>
           </li>
  </ul>

ok, that works, I can display the owner by concatenating the firstName and the lastName. However, it'd be better to have a property FullName somewhere. That property would either return firstname + lastname or 'None' if Person is null.

My problem is that I don't know where to add this property. It feels strange to add it to the contract controller, as it's more related to the Person. But I don't have a Person controller. What would be the approach for this ?

1 Answer 1

2

Assuming you have a Contract service

angular.factory('Contract', ['$resource', function($resource) {
  var Contract = $resource(...);
  ...

  Contract.prototype.getOwner = function() {
    if (this.Person) {
      return this.Person.firstName + this.Person.lastName;
    }
    return 'None';
  }

  return Contract;

}]);

You could then use it as

<h4>Owner: {{contract.getOwner()}}</h4>
Sign up to request clarification or add additional context in comments.

9 Comments

I do have a Contract service and I could do that indeed. Is this a common thing to do ? I know I'm annoying :) But I just want to apply best practices as much as I can from the beginning.
Check out this repo to see more of this and other approaches used github.com/angular-app/angular-app. It seems like a reasonable thing to do. I wouldn't name my properties in PascalCase though (Person vs person)
Be warned: This function will be evaluated on every $digest. Just put a console.log() inside of it and you'll see. It's generally a better idea to process your Contract or Person object when it changes and update the property rather than use a method like this. It's not wrong do to things this way, but it may be less performant, especially in a large repeater.
It's as performant as {{contract.Person && contract.Person.firstName + contract.Person.lastName || 'None'}}, although much more readable. For static bindings, you might want to consider github.com/Pasvaz/bindonce @blesh
It sure is. But that's not quite what I'm suggesting. I'm suggesting the concatenation can be done one time at the time the collection (or object) is updated/created.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.