tabset中的Angular JS Form验证给出错误:TypeError:无法读取未定义的属性'$ valid'

时间:2016-01-07 05:28:03

标签: angularjs twitter-bootstrap

Html:

<tabset> 
    <tab heading="Create CS Sales Order & GRN-VRRE" >
        <form name="motorForm"  novalidate>
            <input type="text" ng-model="ngtext" required />
            <button type="submit" ng-click="CSsalesVRRESave()" >submit</button>
        </form>
    </tab>
    <tab heading="Create CS Sales Order & GRN-VRRE" >
        <div>somthing inside it</div>
    </tab>
</tabset>

Javascript功能

$scope.CSsalesVRRESave = function () {
            console.log($scope.motorForm.$valid);
        }

输出控制台给我错误TypeError:

  

无法读取未定义的属性'$ valid':

注意:如果我删除了tabset,它可以按照要求工作

2 个答案:

答案 0 :(得分:4)

var app = angular.module('testApp', [ ]);

app.controller('testController', ['$scope', '$location', function ($scope, $location) {

$scope.CSsalesVRRESave = function (motorForm) {
     if(motorForm.$valid==true){
  
  alert($scope.ngtext)
  } else{
    alert("Please Enter some value");
    }
};
  
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp"  ng-controller="testController">
<tabset> 
    <tab heading="Create CS Sales Order & GRN-VRRE">
        <form name="motorForm"  novalidate>
            <input type="text" ng-model="ngtext" ng-required="true"/>
            <button type="submit" ng-click="CSsalesVRRESave(motorForm)">submit</button>
        </form>
    </tab>
    <tab heading="Create CS Sales Order & GRN-VRRE">
        <div>somthing inside it</div>
    </tab>
</tabset>
  </body>

<tabset> 
    <tab heading="Create CS Sales Order & GRN-VRRE">
        <form name="motorForm"  novalidate>
            <input type="text" ng-model="ngtext" required/>
            <button type="submit" ng-click="CSsalesVRRESave(motorForm)">submit</button>
        </form>
    </tab>
    <tab heading="Create CS Sales Order & GRN-VRRE">
        <div>somthing inside it</div>
    </tab>
</tabset>


$scope.CSsalesVRRESave = function (motorForm) {
    console.log(motorForm.$valid);
};

答案 1 :(得分:2)

我没有足够的业力来评论,而Nelson的回答是有效的,但你首先看到问题的原因是tabsets创建了一个新的子$ scope,所以motorForm是该标签的一部分{{1 }}。 $scope转到父ng-click中的函数,该函数没有该格式。

另一种方法是让您的表单成为父$scope上的整体表单对象的值,这样它们将通过引用访问,并且它将执行您期望的操作。喜欢 - 在您的控制器中有$scope,然后在您的模板中有

$scope.forms = {}

而不是您的正常形式。