简体   繁体   English

AngularJS范围内未定义的表格

[英]Form undefined in scope in AngularJS

I have a main JS file which holds a bunch of functions which are used throughout my app. 我有一个主要的JS文件,其中包含许多在我的应用程序中使用的函数。 In this JS file I set the routing of the app. 在此JS文件中,我设置了应用程序的路由。

main.js (MainController):

    $stateProvider
    .state('page1', {
        url : '/',
        templateUrl : 'page1.html',
        controller : "Page1Controller"
    })
    .state('page2', {
        url : '/',
        templateUrl : 'page2.html',
        controller : "Page2Controller"
    });`

In Page 2 I have a form 在第2页中,我有一个表格

<div class="outer" ng-controller="MainController">
    <div class="page" ng-init="test();">
        <form id="page2_form" name="page2_form"> 
            <input type="text" id="field1" name="field1"/>
            <input type="text" id="field2" name="field2"/>
        </form>
    </div>
</div>

I will be using the scope to check the form for validation but currently it is undefined. 我将使用合并范围检查表单以进行验证,但目前尚未定义。 I am checking this by using the $scope.$watch . 我正在使用$scope.$watch

page2.js (Page2Controller):

    $scope.$watch('page2_form', function(page2_form) {
        console.log(page2_form);
    });

But it is printing out "undefined". 但是它正在打印“未定义”。 I assume that the routing is actually loading in the controller as the ng-init works. 我假设路由实际上是在ng-init工作时加载到控制器中的。 However, It does work if I try adding ng-controller="Page2Controller" to <div class="page"> this outputs the form on the $scope.$watch which is what I want but it is running it twice since the controller is being loaded twice. 但是,如果我尝试将ng-controller="Page2Controller"<div class="page"> ,它确实可以在$ scope。$ watch上输出表单,这是我想要的,但是自控制器以来它运行了两次被加载两次。

Why is it not outputting the form even though the controller is being loaded in by the routing? 即使通过路由加载了控制器,为什么仍不输出表格?

UPDATE UPDATE

My fix: 我的解决方法:

Adding $scope.form = {}; 添加$scope.form = {}; to page2.js (Page2Controller) and changing the form to this: page2.js (Page2Controller)并将表单更改为此:

<form id="form.page2_form" name="form.page2_form"></form>

This means that I can now access fields in the form with 这意味着我现在可以使用以下方式访问表单中的字段

$scope.form.page2_form[fieldname]

However, I'm not sure why I have to do this now as I have past applications where I did not need to do the form.form_name aspect of it. 但是,我不确定为什么现在必须执行此操作,因为在过去的应用程序中,我不需要执行它的form.form_name方面。

I think your problem is related to JavaScript ProtoTypal inheritance and how Angular.js handling that in 'ng-*' directives. 我认为您的问题与JavaScript ProtoTypal继承以及Angular.js如何在“ ng- *”指令中处理该问题有关。 Kindly check that link for more deep understanding to that topic. 请检查该链接,以更深入地了解该主题。 https://github.com/angular/angular.js/wiki/Understanding-Scopes https://github.com/angular/angular.js/wiki/Understanding-Scopes

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

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