Ng-include - the controller is called several times

Situation

I am trying to enable partial with ng-include without the need for any routing. I just want to include a specific partial of many dynamically. It more or less looks like this:

 <div ng-controller="SomeController"> //This controller defines a $scope.getPartial(id) <ng-include src="getPartial(something.id)"></ng-include> </div> 

It works, part is on. But, looking at the console, I see that the controller is called several times, and on the first call I get 404

GET path / to / partials / undefined.html [HTTP / 1.1 404 not found 162ms]

it seems that something.id is not defined when the inclusion is done for the first time.

Questions

  • How can I just enable partial without creating a new area?
  • If this is not possible, how can I make sure the controller is called only once?
  • and how can i avoid 404?

I am new to AngularJS and therefore may be mistaken in assumptions about things or miss obvious things, please enlighten me.

+7
source share
1 answer
  • ngInclude creates a new scope by definition, so you cannot get around it easily. And, since nested areas are inherited from each other, your newly created area will be able to read everything that is in your SomeController , so you should not have problems with the new area. Attribute
  • ngInclude src will be reevaluated in every $ digest amount, so you cannot stop it from calling the controller method again. In this case, you need to make sure that your method is light and fast, and it returns the same output as the same input
  • You can avoid the original 404 by returning an empty string "" when id is not yet defined:

 $scope.getPartial = function(id){ if(!id){ return ""; } ... } 
+6
source

All Articles