我有以下代码:
<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“是未定义的。
有没有办法可以将表单的内容设置为原始的。我认为这是一个范围问题,但我不确定如何解决它。我尝试了一种解决方案,即删除第二个include并直接粘贴代码。这个解决方案是可行的。
然而,我们希望能够重用代码,所以我希望能够通过包含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。
发布于 2013-07-07 01:28:13
这个答案将打破所有规则(即,在控制器中遍历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的$element
中查找form
元素,选择第一个元素,然后获取它的FormController。
如果只是由于某些用户交互而调用$setPristine()
,则不需要查找$includedContentLoaded
事件-我之所以要这样做,只是因为我不想创建任何UI组件来触发操作,并且当控制器第一次运行时,窗体还不存在。
另请参阅AngularJS: Access formController of a form placed inside transcluded directive from parent controller,它解决了试图从父级访问子进程的类似问题。
一种更简洁的解决方案:定义一个指令(在ng-include元素上使用它),并将AdminController函数作为属性传递给它。在指令的链接函数中,调用该方法并将FormController作为参数传递。则AdminController将具有对所需FormController的引用。(我没有费心对此进行编码,因为我不确定您是否需要一个必须与ng-include一起使用指令的解决方案。)
发布于 2013-07-09 21:29:37
好吧,一种方法是广播一个事件,就像这样:
angular.module('myApp',[])
.controller('AdminCtrl',function($scope){
$scope.modalReset = function(){
$scope.$broadcast('modal-reset');
};
})
.controller('ModalCtrl', function($scope){
$scope.$on('modal-reset', function(){
$scope.itemForm.$setPristine();
});
});
这样你就不必遍历dom了。
发布于 2015-10-30 05:21:58
不要违反规则:)只需在控制器中定义变量(空对象),并在定义表单时使用它。因为angular JS在幕后使用作用域原型,所以当form尝试访问内部作用域(以引导变量)时,它将首先通过作用域链,并尝试在父作用域中找到相同的变量。
<!—- The vars should live in the controller. I placed them here for the example. -—>
<div ng-controller=“controllerName” ng-init="form={}; model={}" >
<div ng-include=“ ‘path-to-the-template’ ”></div>
</div>
<!—- Inside path-to-the-template -—>
<form name="form.createUser">
<input name="name" ng-model="model.name" />
<input name="email" ng-model="model.email" />
</form>
参考http://blog.152.org/2014/07/angular-form-element-not-attaching-to.html的链接
https://stackoverflow.com/questions/17474045
复制相似问题