AngularJS - HTML 在 ng-repeat 中丢失模板替换范围
AngularJS - HTML losing scope on template replace in ng-repeat
我的 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>
方法 addExercise()
向可变部分添加了一个新元素,因此使用另一个模板(由指令 new-exercise
表示)更新了 html。
即
$scope.addExercise = function(){
$scope.sections.push({
title: "hello",
content: "fsa"
});
}
指令new-exercise
:
.directive('newExercise', function () {
return {
templateUrl: '/templates/exercise-form.html',
replace: true,
}
})
模板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>
我希望模板 exercise-form.html
将输入中的值更新为 hello
但范围为空。
但是,如果我删除该指令并在 ng-repeat 下添加模板 html,它会按我预期的那样工作。我觉得范围由于指令而丢失,但不确定确切原因。谁能解释一下原因以及如何解决?
谢谢。
删除指令中的 replace: true
。
更正以下指令:
.directive('newExercise', function () {
return {
templateUrl: '/templates/exercise-form.html'
}
})
我的 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>
方法 addExercise()
向可变部分添加了一个新元素,因此使用另一个模板(由指令 new-exercise
表示)更新了 html。
即
$scope.addExercise = function(){
$scope.sections.push({
title: "hello",
content: "fsa"
});
}
指令new-exercise
:
.directive('newExercise', function () {
return {
templateUrl: '/templates/exercise-form.html',
replace: true,
}
})
模板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>
我希望模板 exercise-form.html
将输入中的值更新为 hello
但范围为空。
但是,如果我删除该指令并在 ng-repeat 下添加模板 html,它会按我预期的那样工作。我觉得范围由于指令而丢失,但不确定确切原因。谁能解释一下原因以及如何解决?
谢谢。
删除指令中的 replace: true
。
更正以下指令:
.directive('newExercise', function () {
return {
templateUrl: '/templates/exercise-form.html'
}
})