Pregunta

Situation:

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

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

It works, the partial is included. But looking at the console I can see that the controller is called several times and the first time it is called, I get a 404

GET path/to/partials/undefined.html [HTTP/1.1 404 Not Found 162ms]

it seems that something.id is not defined, when the include is made for the first time.

Questions:

  • how can I simply include a partial, without creating a new scope?
  • if that's not possible, how can I make sure, the controller is called only once?
  • and how can I avoid the 404?

I'm fairly new to AngularJS and may therefore make wrong assumptions about stuff or miss obvious things, please enlighten me.

¿Fue útil?

Solución

  1. ngInclude creates a new scope by definition so you can't easily circumvent it. And, since nested scopes inherit from each other your newly created scope will be able to read whatever is in your SomeController, so you shouldn't have any problems with new scope.
  2. ngInclude's src attribute will get re-evaluated on each $digest scope, so you can't stop it from calling your controller's method repeatedly. For that matter you need to make sure your method is light and fast and it returns the same output given the same input
  3. You may avoid initial 404 by returning empty string "" when id is not yet defined:

 

$scope.getPartial = function(id){
  if(!id){
    return "";
  }
  ...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top