angularjs - 使用 ng-include 插入表单时如何验证表单

标签 angularjs

我有 3 个不同的表单页面,它们使用 ng-include 插入到引导模式窗口中的 DOM 中。在这种情况下,在每个表单中进行验证并提交完整表单(对于所有 3 个表单)的最佳方法是什么?

HTML

<div ng-switch on="page">
    <div ng-switch-when="Games">
        <div ng-include="'Games.html'"></div>
    </div>  
    <div ng-switch-when="Music">
        <div ng-include="'Music.html'"></div>
    </div>
    <div ng-switch-when="Videos">
        <div ng-include="'Videos.html'"></div>
    </div>
</div>

演示:http://plnkr.co/edit/D1tMRpxVzn51g18Adnp8?p=preview

最佳答案

还需要找到一种方法来验证数据 (可能与 jqueryvalidation 一起)但可以作为一个起点。 我认为没有办法获得游戏的值(value)。$valid 所以我想到了

var app = angular.module("myApp", [])
            app.controller("FormsCtrl", function($scope) {
               //console.log($scope);
               // $scope.items = ['Games', 'Music', 'Videos'];
                $scope.$on('someEvent',function(e,a){
                   console.log(a); 
                })
            });
            app.directive("myform", function() {
                return {
                    restrict: "A",
                    link:function(scope,element,attrs){
                        element.bind('submit',function(e){
                            var isValid = false; // TO DO :)
                            scope.$emit('someEvent', [attrs.fname,isValid]);
                        });
                    }
                }
            });



<div ng-controller="FormsCtrl"> 
      <div ng-switch on="page">
            <div ng-switch-when="Games">
                <div ng-include="'Games.html'"></div>
            </div>  
            <div ng-switch-when="Music">
                <div ng-include="'Music.html'"></div>
            </div>
            <div ng-switch-when="Videos">
                <div ng-include="'Videos.html'"></div>
            </div>
    </div>
</div>


<form name="games"  class="simple-form"  myform fname="games">
   <input type="text" ng-model="prefix.games.name" name="uName" required /><br>
</form>

编辑 更聪明、更快捷的方法:)

app.controller("FormsCtrl", function($scope) {
                $scope.mySubmit = function(isValid){
                    console.log(isValid);
                }
            });


<form name="games"  class="simple-form" ng-submit="mySubmit(games.$valid)">
   <input type="text" ng-model="prefix.games.name" name="uName" required /><br>
</form>

关于angularjs - 使用 ng-include 插入表单时如何验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20722180/

相关文章:

javascript - 如何在 AngularJS 1 中使用 ng-view 显示 View ?

angularjs - 等待 Protractor 与页面 : "window. 同步时出错 Angular 未定义

javascript - 以小时和分钟显示时间 (00 :00) and round seconds to minutes

javascript - 使用 Angular 指令禁用文本选择

asp.net-mvc - 使用带有 AngularJS 的 jQuery 验证的 Razor View

javascript - 基于html属性为gulp构建过程添加条件

angularjs - AngularJS 过滤器中的无限摘要循环

AngularJS - 绑定(bind)/监视返回 promise 的函数

javascript - 选择选项不与 ng-model 绑定(bind)

javascript - karma Jasmine 单元测试出现未知提供者错误