加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:06:04 所属栏目:安全 来源:网络整理
导读:我有以下代码: 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-in
我有以下代码:
<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控制器中,我尝试使用以下代码将表单重置为原始:

$scope.itemForm.$setPristine();

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

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

但是我们希望能够重用代码
所以我想用modal.html的include来做到这一点

请注意,我们想要这样做的原因是因为我们的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。

这个答案将会破坏所有的规则(即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包含的内容加载,然后从定义AdminController的$元素,我们查找表单元素,选择第一个,然后获取其FormController。

Plunker

如果您只是通过某些用户交互调用$ setPristine(),则不需要查找$ includedContentLoaded事件 – 我只需要这样做,因为我不想创建任何UI组件来触发操作,当控制器首次运行时,表单不存在。

另请参阅AngularJS: Access formController of a form placed inside transcluded directive from parent controller,其中涉及到尝试从父级访问子级的类似问题。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读