Vishal Sh Vishal Sh - 4 months ago 9
AngularJS Question

AngularJS - HTML losing scope on template replace in ng-repeat

I have the following code in my html.

<div id="section">
<div new-exercise ng-repeat="section in sections track by $index">
</div>
</div>

<div class="add_exercise add_exercise_btn">
<a class="add_exercise_link" ng-click="addExercise()">
<span>+ Add an Exercise</span>
</a>
</div>


the method
addExercise()
adds a new element to the variable sections, hence updating the html with another template (represented by directive
new-exercise
).

i.e.

$scope.addExercise = function(){
$scope.sections.push({
title: "hello",
content: "fsa"
});
}


The directive
new-exercise
:


.directive('newExercise', function () {
return {
templateUrl: '/templates/exercise-form.html',
replace: true,
}
})


The template
exercise-form.html
:


<div class="add_exercise" id="add_exercise_form" data-section-id="{{id}}">
<form class="new_section">
<div class="input-box">
<input id="title" type="text" name="title" class="form-control" value="{{section.title}}" ng-model="section.title">
<label for="title">Exercise Name</label>
<span class="help-block"></span>
<span>{{ section.title }}</span>
</div>
</form>
</div>


I expect the template
exercise-form.html
to update the value inside input to be
hello
but the scope is empty.

However, if I remove the directive and add the template html under ng-repeat it works as I expect. I feel that the scope is lost due to directive, but not so sure about the exact reason. Can anyone explain me the reason and how to resolve?

Thanks.

Answer

Remove the replace: true in your directive.

Corrected directive given below:

.directive('newExercise', function () {
  return {
      templateUrl: '/templates/exercise-form.html'
  }
})
Comments