2

I have this object:

function Boy(n,s,a)
{
    this.name = n;
    this.surname = s;
    this.age = a;

    this.getInfo = function(){
        return this.name + ' ' + this.surname + ' (' +  this.age + ')';
    }
}

I want to do something like this:

{{ boy.getInfo() }}

and not like this:

{{ boy.name }} {{ boy.surname }} ({{boy.age}})

is it possible?

there are some tricks for doing something similar?

1
  • Yep, that's totally fine. Just keep in mind that binding to functions can be expensive because the function will be executed much more often than you might expect. In your case that shouldn't be a big problem as the function body isn't doing crazy expensive stuff. If you do crazy expensive stuff, it's better to cache the result of the function and bind to that. Commented Mar 28, 2014 at 0:27

3 Answers 3

4

Absolutely! You can create an object and shove it into $scope just like anything else.

var NameController = function ($scope) {
   $scope.boy = new Boy("Foo", "Bar", 32);
};
NameController.$inject = ['$scope'];

app.controller("NameController", NameController);

And then bind it in the UI just like so:

<h3>{{boy.getInfo()}}</h3>

Here is an example of binding to all three properties and seeing the result of the function: http://jsfiddle.net/jwcarroll/Pb3Cu/

Sign up to request clarification or add additional context in comments.

2 Comments

Is that fiddle meant for another question?
@bhollis - HA! I tend to fork previous fiddles to answer new questions, but it looks like in that case I just updated without actually creating the fork. I've fixed the link back to what it should be. Thanks for catching this!
2

You can bind $scope functions normally

function MyController($scope){
    $scope.myfunc = function(){
        return "test";
    }
}

and then, in the view

{{ myfunc() }}

Comments

1

You can do something like:

function Boy(n,s,a)
{
    this.name = n;
    this.surname = s;
    this.age = a;

    this.getInfo = function(){
        return this.name + ' ' + this.surname + ' (' +  this.age + ')';
    }
}
var boy = new Boy(n, s, a);

$scope.boy = function(){
  return boy.getInfo();
}

And in you template just bind {{boy()}}.

Comments

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.