【问题标题】:Angular form not available in scope角度形式在范围内不可用
【发布时间】:2016-12-05 10:35:17
【问题描述】:

我在控制器中有一个表单,该表单仅在用户按下指令内的按钮时加载,在该指令上使用 $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>

控制器功能

$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

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

【问题讨论】:

    标签: javascript angularjs forms validation asynchronous


    【解决方案1】:

    表单未定义的原因是因为 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>
    

    【讨论】:

    • 很高兴它有帮助:)
    【解决方案2】:

    我设法通过使用ng-show 而不是ng-if 解决了这个问题

    【讨论】:

      猜你喜欢
      • 2014-06-10
      • 2015-12-10
      • 2015-02-02
      • 1970-01-01
      • 2021-02-16
      • 2017-05-30
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多