7

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.

1 Answer 1

6
  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 "";
  }
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1. I would also like to add that in angular lot's of things will be called multiple times or sometimes unexpected times. You need to shift your understanding from imperative to declarative. Think css. You don't care(normally) how many times the browser repaints, reflows based on style/class changes
Thanks, it seems a bit hacky but maybe I'm just not used to the repaint paradigma ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.