0

Is there a trick to send the Model attribute functions over Http gets ?

so assuming i have a model User :

 attributes: {
     last_name : "string" ,  
     first_name: "string",
  name : function()
     {
        return this.first_name + " " + this.last_name;
     }
  }

Controller :

User.findOne( { id : 1}).exec(function(err,user) {
   res.view("profile", {user:user}); 
});

and a view :

<div> 
  <h4> hi <%= user.name() %>
</div>

everything works perfectly.

however if I am loading the data through a client : Controller :

User.findOne( { id : 1}).exec(function(err,user) {
   res.json({user:user}); // or res.send({user: user});
});

and in Client (Angular):

$http.get("/controller/method/").then(function(data){
$scope.user = data;
});

the view cannot do that anymore as easy as it used to :

<div>
 <h4> hi {{ user.name() }} </h4>
</div>

Any ideas or workarounds ? I tried overwriting the toJSON method of the model but no luck. would appreciate any ideas here.

Adham
  • 490
  • 4
  • 12

1 Answers1

1
 attributes: {
     last_name : "string" ,  
     first_name: "string",
  name : function()
     {
        return this.first_name + " " + this.last_name;
     }
  },
    toJSON : function(){
      var obj = this.toObject();
      obj.name = this.first_name + " " + this.last_name;
      return obj;
    }
Meeker
  • 5,979
  • 2
  • 20
  • 38
  • ok sounded legit in the beginning but its not really working with me. I dont think this function is really being called, i added a console log statement inside got nothing on calling it. did you test it before ? – Adham Dec 18 '14 at 10:43
  • ok got around it, toJSON is an attribute function it has to be inside the attributes object. I also cant send functions – Adham Dec 18 '14 at 10:49
  • My example is on the attributes object? This method works, fully tested. – Meeker Dec 18 '14 at 14:48