As you know, it is possible to initialize objects as follows:
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
Is it possible to define object similar like this but via a function:
<div ng-init="init()">
My aim is actually taking the objects from an API and show them in a list via ng-repeat
The documentation says
ng-init
will take any expression. So yes, you can do what you want above as long as the associated scope defines a function calledinit()
(and I also verified it for fun).Note that the documentation says that
ng-init
is really only intended to be used for aliasing properties inside of anng-repeat
:Finally, note that you can simply initialize your variables when the controller is created. So there's really no need to use
ng-init
at all. For example: