gpt4 book ai didi

angularjs - 如何将包含在 ng-include 中的表单设置为 prestine?

转载 作者:行者123 更新时间:2023-12-03 14:55:38 25 4
gpt4 key购买 nike

我有以下代码:

<div modal="modal.shouldBeOpen" close="close()" options="opts">
<div class="modal-body">
<form novalidate name="itemForm" style="margin-bottom: 0px;">

包含在包含的文件 modal.html 中

<div data-ng-controller="AdminController">
<ng-include src="'/Content/app/admin/partials/grid-subject.html'"></ng-include >
<ng-include src="'/Content/app/admin/partials/modal.html'"></ng-include>
</div>

在我的 AdminController Controller 中,我尝试使用以下代码将表单重置为原始状态:

$scope.itemForm.$setPristine();

当我这样做时,它告诉我“itemForm”未定义。

有没有办法可以将表单的内容设置为原始内容。我认为这是一个范围问题,但我不知道如何解决它。一世
尝试了删除第二个包含并直接粘贴代码的一种解决方案。此解决方案有效。

但是我们希望能够重用代码
所以我希望能够通过包含 modal.html 来做到这一点

请注意,我们想要这样做的原因是因为我们的 modal.html 上有如下内容:
    <button
class="btn float-right"
data-ng-disabled="itemForm.$pristine"
data-ng-click="modalReset()"
data-ng-show="modal.resetButton">
Reset</button>
</form>

所以我们实际上是在 itemForm 里面,并且想从里面的按钮将它设置为 $pristine。

最佳答案

这个答案将打破所有规则(即, Controller 内的 DOM 遍历),但无论如何......

.controller('AdminController', ['$scope','$element',
function($scope, $element) {
$scope.$on('$includeContentLoaded', function() {
var childFormController = $element.find('form').eq(0).controller('form');
console.log(childFormController);
childFormController.$setPristine();
});
}]);

我们等待包含 ng 的内容加载,然后从 $element在定义 AdminController 的地方,我们寻找 form元素,选择第一个,然后获取它的 FormController。

Plunker

如果您只调用 $setPristine()由于某些用户交互,您无需查找 $includedContentLoaded事件——我只需要这样做,因为我不想创建任何 UI 组件来触发操作,并且当 Controller 第一次运行时,表单还不存在。

另见 AngularJS: Access formController of a form placed inside transcluded directive from parent controller它处理了试图从 parent 那里访问 child 的类似问题。

更简洁的解决方案:定义一个指令(在 n​​g-include 元素上使用它)并将 AdminController 函数作为属性传递给它。在指令的链接函数中,调用该方法并将 FormController 作为参数传递。然后 AdminController 将具有对所需 FormController 的引用。 (我没有费心编写这个代码,因为我不确定你是否想要一个必须使用指令和 ng-include 的解决方案。)

关于angularjs - 如何将包含在 ng-include 中的表单设置为 prestine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17474045/

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