简体   繁体   English

为什么我无法在angularJS的ngInclude内访问表单对象?

[英]Why I can't access a form object inside a ngInclude on angularJS?

I have a screen built with a several stacks of ng-includes. 我有一个屏幕,其中包含几堆ng-includes。 The last one, in special, I build the screen based on user configuration. 最后,特别是我根据用户配置来构建屏幕。

Sometimes, I have to show a Form in one of this included templates. 有时,我必须在其中一个包含的模板中显示一个表单。 And when my user click on save button, I have to validate if all fields in the form are valid. 当我的用户单击“保存”按钮时,我必须验证表单中的所有字段是否有效。

In the meantime, when a try to access form object, to check for $valid, my form is undefined. 同时,当尝试访问表单对象以检查$ valid时,我的表单未定义。

After a day fighting against it, I've discovered that ng-include process is not accepting my form object to be created. 经过一天的努力,我发现ng-include进程不接受要创建的表单对象。

I've created this plunker to see if it's really happening on a simple project, making a working form and not working one: http://plnkr.co/edit/4oMZYLgaYHJPoSZdSctI?p=preview 我创建了这个插件,以查看它是否真的在一个简单的项目中发生,创建了一个有效的表单而不起作用: http ://plnkr.co/edit/4oMZYLgaYHJPoSZdSctI?p=preview

Basically, created a form, like this, with demanded angular attributes: 基本上,创建一个具有所需角度属性的表单,如下所示:

<form name="sampleForm">
    <input type="text" name="aws" required ng-model="myValue">
    <br/>myValue: "{{ myValue }}"
    <br/>

    <input type="text" name="aws" required ng-model="myValue">
    <br/>myValue: "{{ myValue }}"
</form>

And trying to access form object like this: 并尝试像这样访问表单对象:

$scope.sampleForm.aws.$valid

And the result is: 结果是:

$scope.sampleForm === undefined

Someone know how to solve this problem? 有人知道如何解决这个问题吗?

Since ng-include creates a new scope, $scope.sampleForm will be undefined from within the included page. 由于ng-include创建了一个新的作用域, $scope.sampleForm在包含的页面中将未定义$scope.sampleForm

The solution should be getting the ng-controller="formController" declaration inside of the included HTML page itself, which I think is also a better design, since I can't see a scenario where it's not "controlling" the form. 解决方案应该是在包含的HTML页面本身内部获取ng-controller="formController"声明,我认为这也是一个更好的设计,因为我看不到它不是“控制”表单的情况。

The other non-included form obviously works as you might expect. 显然,其他未包含的表格也可以按照您的预期工作。

Plunker Plunker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM