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

Ala*_*an2 16 angularjs

我有以下代码:

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

哪个包含在包含的文件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>
Run Code Online (Sandbox Code Playgroud)

在我的AdminController控制器中,我尝试使用以下代码将表单重置为pristine:

$scope.itemForm.$setPristine();
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它告诉我"itemForm"是未定义的.

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

但是我们希望能够重用代码,所以我希望能够使用include for 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>
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*cok 10

这个答案将打破所有规则(即在控制器内部进行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();
  });
}]);
Run Code Online (Sandbox Code Playgroud)

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

Plunker

如果你只是$setPristine()因为一些用户交互而调用,你将不需要查找$includedContentLoaded事件 - 我只需要这样做,因为我不想创建任何UI组件来触发操作,以及何时控制器首先运行,表单尚不存在.

另请参阅AngularJS:访问来自父控制器的transcluded指令内的表单的formController,它处理尝试从父级访问子级的类似问题.

更清晰的解决方案:定义指令(在ng-include元素上使用它)并将AdminController函数作为属性传递给它.在指令的link函数中,调用该方法并将FormController作为参数传递.然后AdminController将引用所需的FormController.(我没有打扰这个编码,因为我不确定你需要一个解决方案,你必须使用指令和ng-include.)