gpt4 book ai didi

javascript - AngularJS - 在 ng-repeat 中替换模板的 HTML 丢失范围

转载 作者:行者123 更新时间:2023-11-30 00:05:41 25 4
gpt4 key购买 nike

我的 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() 方法将一个新元素添加到可变部分,从而使用另一个模板更新 html(由指令 new-exercise 表示)。

$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 将 input 中的值更新为 hello 但范围是空的。

但是,如果我删除该指令并在 ng-repeat 下添加模板 html,它会按我预期的那样工作。我觉得范围由于指令而丢失,但不确定确切原因。谁能解释一下原因以及如何解决?

谢谢。

最佳答案

删除指令中的 replace: true

更正指令如下:

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

关于javascript - AngularJS - 在 ng-repeat 中替换模板的 HTML 丢失范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com