javascript - Angular 形式在范围内不可用

标签 javascript angularjs forms validation asynchronous

我在 Controller 中有一个表单,仅当用户按下指令内的按钮时才加载该表单,事件在该指令上使用 $emit 进行中继。但我的问题是表单在范围内不可用,因此表单的验证始终无效。 这是我的 html,

<directive></directive>

<div class="col-md-12 editForm" ng-if="editMode">
    <form name="editPollForm" id="editPollForm" ng-submit="editPoll()" novalidate>
        <md-input-container>
             <inpu ng-model="payload.a" required>
        </md-input-container>

        <md-input-container>
             <inpu ng-model="payload.b" required>
        </md-input-container>

         <button type="submit" ng-disabled="editPollForm.$invalid"> Save</button>
    </form>
</div>

Controller 功能

$scope.$on('pollEditFormRequested', function(event){
    $scope.payload = {};
    $scope.payload.a = 'a';
    $scope.payload.b = 'b';

    $scope.editMode = true;
    console.log($scope.editPollForm);
});

$scope.editPoll = function(){
    console.log($scope.editPollForm);
    //call my submit edit form api

};

在指令生成的 $emit 上被捕获并填充值,一切正常,但提交按钮保持禁用状态,因为 ediPollForm 在每个 console.logs 上输出 undefined/p>

我做错了什么?我尝试了 $timeout$apply 但无济于事。

最佳答案

表单未定义的原因是因为 ng-if 创建了一个新的子作用域,因此父作用域对新表单一无所知。 为了让它知道您应该将表单包装在父对象中。

$scope.form = {} //with this object the parent will hold a reference to the form 
//created in the child scope

$scope.$on('pollEditFormRequested', function(event){
    $scope.payload = {};
    $scope.payload.a = 'a';
    $scope.payload.b = 'b';

    $scope.editMode = true;
    console.log($scope.form.editPollForm); //here the form will be undefined 
    //because it's not created yet
});

$scope.editPoll = function(){
    console.log($scope.form.editPollForm);
    //call my submit edit form api

};

在你的模板中:

<div class="col-md-12 editForm" ng-if="editMode">
 <!--new scope here-->
    <form name="form.editPollForm" id="editPollForm" ng-submit="editPoll()" novalidate>
        <md-input-container>
             <inpu ng-model="payload.a" required>
        </md-input-container>
        <md-input-container>
             <inpu ng-model="payload.b" required>
        </md-input-container>
         <button type="submit" ng-disabled="editPollForm.$invalid"> Save</button>
    </form>
</div>

关于javascript - Angular 形式在范围内不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972200/

相关文章:

javascript - 为什么我不能在某些 Jetpack 代码处设置断点?

javascript - $routeProvider 和 angularJS?

javascript - ng-显示不工作 Angular

javascript - 如何使用 handleSubmit 内的 Formik promise 来更改 react 状态以显示/隐藏 div?

forms - 如何在 PrestaShop 中自定义注册表和联系表单?

javascript - 如何在 jQuery 更改事件后获取更新的 URL 参数

JavaScript 与 Node.js

javascript - 单击时不显示标记上的 MapBox 弹出窗口描述

angularjs - 基于 token 的身份验证 - 安全漏洞?

php - Laravel 表单操作 URL