Gerard Simpson Gerard Simpson - 1 year ago 133
AngularJS Question

ng-init vs function in controller, which is better practice when using $parent?

I have a Bootstrap modal which corresponds to a ng-repeat list. I would like to access the ng-repeat scope data from its parent, which contains the modal. I do this so that when the modal button is clicked on the list, the corresponding data from the JSON appears in the modal.

I have found 2 ways of doing this, and I wonder which is the best alternative?

Method 1

<li ng-init="myFunction(item,$parent)" ng-repeat="item in data.webapps_1.items>


$scope.myFunction = function(item,parent){

Method 2 View:

<li ng-init="$parent.selected=item.counter-1" ng-repeat="item in data.webapps_1.items>

With nothing in the controller.

I have read in the Angular ngInit docs that

The only appropriate use of ngInit is for aliasing special properties
of ngRepeat, as seen in the demo below. Besides this case, you should
use controllers rather than ngInit to initialize values on a scope.

But the list of special properties of ngRepeat does not include $parent.

So, which is the better practice? Including the expression
in the controller or in ngInit directive?

Thanks in advance

Answer Source

Either of the two fine really, so long as you're consistent. Depends on the scale of the app though.

IMO if the app is going to be large you'll want to go the function way, to better adhere to the whole MVC philosophy of decoupling and separation of concerns (


It's a better structure because you want to keep most of your business logic in the javascript controllers, not in the view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download