1

I have a template which I want to use in many parts of my application. The template contains select box with a model assigned.

I include the template by the means of ng-include.

<span ng-include="'templateWorking'" ng-init="selectModel=data.field"></span>

and then in template:

<script type="text/ng-template" id="templateWorking">
   <select ng-model="selectModel">
  <option value="Test1">Test1</option>
  <option value="Test2">Test2</option>
</select>

Of course, it does not work since ng-include creates a new child scope. It is possible to get it work when I use one model (using dot . in a model like data.model).

But how it is possible in this particular case so I can use this template with different models in different controllers? Besides, I need to dynamically attach a handler to the select (e.g. ng-change="doSmth()").

Thanks in advance.

For the reference: http://plnkr.co/edit/NiLQyVQGb6X1mA0sVvA1?p=preview

Sray
  • 665
  • 4
  • 13
  • 25
  • Typically, if you need reusability, it's best to create a directive. You would have full control of the scope. – New Dev Oct 18 '14 at 17:22

1 Answers1

1

In this case it was best to use a directive instead. You can get some control over ng-include by using onload but if that's not enough, using a directive is your best bet.

Reference: Difference between onLoad and ng-init in angular

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
  • Unfortunately, this is not related to the issue. The origin of the problem is the fact ng-include creates a new child scope regardless ng-init or onLoad is used. So I wonder how to deal with it. You can see the plunk above to see. I updated it. – Sray Oct 18 '14 at 16:23
  • Ok. I understand better what you are after. Let me think a bit. :) – Juho Vepsäläinen Oct 18 '14 at 16:26
  • Maybe this isn't the answer you are looking for but I would just push the template inside a directive. That would give you more control over scoping and probably make it more maintainable as well. – Juho Vepsäläinen Oct 18 '14 at 16:35
  • After some additional digging it seems there is no way to get it work with ng-include so, yes, you're right. Directives seems to be the only possible way to achieve the desired. Thank you. – Sray Oct 18 '14 at 18:44
  • Ok. I rewrote the answer to reflect that. Thanks. :) – Juho Vepsäläinen Oct 19 '14 at 05:29