javascript - AngularJS 表单验证中的 ng-class

标签 javascript angularjs forms

我对以下有关 angularJS 表单验证的代码感到困惑。请参阅下面的 HTML 表单和 JavaScript 代码,这是我们的讲师给出的示例代码。我不明白的是这个标签

    <div class="form-group" ng-class="{ 'has-error': feedbackForm.firstName.$error.required && !feedbackForm.firstName.$pristine }">

在 ng-class ="{...}"中,“feedbackForm”是表单的名称,但“firstName”是 $scope.feedback 对象的属性,如 JavaScript 中所述代码。什么机制将它们连接在一起以便可以通过“feedbackFrom.firstName”访问?

此外,“feedbackForm.firstName”后面的“$error”和“$pristine”是什么?它是 AngularJS 预定义的对象吗?再说一次,如何使用句点来访问它们?

HTML 表单:

<div ng-controller="FeedbackController">
    <form role="form" name="feedbackForm" ng-submit="sendFeedback()" novalidate>
      <div class="form-group" ng-class="{ 'has-error': feedbackForm.firstName.$error.required &&!feedbackForm.firstName.$pristine }">
       <label for="firstname" class="col-sm-2 control-label">First Name</label>
       <div  class="col-sm-10">
        <input type="text" class="form-control" id="firstname" name="firstname" placeholder="Enter First Name" ng model="feedback.firstName" required>
        <span ng-show="feedbackForm.firstName.$error.required && !feedbackForm.firstName.$pristine" class="help-block">Your first name is required.</span>
       </div>
      </div>
    </form>

相关JavaScript代码:

    .controller('ContactController', ['$scope', function($scope) {

     $scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };

     var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];

    $scope.channels = channels;
    $scope.invalidChannelSelection = false;

    }])

   .controller('FeedbackController', ['$scope', function($scope) {

    $scope.sendFeedback = function() {

    console.log($scope.feedback);

    if ($scope.feedback.agree && ($scope.feedback.mychannel == "")) {
       $scope.invalidChannelSelection = true;
       console.log('incorrect');
      }
    else {
       $scope.invalidChannelSelection = false;
       $scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
       $scope.feedback.mychannel="";
       $scope.feedbackForm.$setPristine();
       console.log($scope.feedback);
       }
     };
  }])

最佳答案

你有点不对劲。

feedbackForm.firstName 引用表单 feedbackForm 和输入字段 firstName

$scope.feedback 对象由 ngModel 引用并处理模型绑定(bind)。

$error$pristine 是 AngularJS 添加的类,用于指示输入字段的状态。

关于javascript - AngularJS 表单验证中的 ng-class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34212194/

相关文章:

javascript - 当域和协议(protocol)匹配时获取 iframe 内容高度,但子域不匹配

javascript - 我如何更改我当前的代码以将我的 div 设置为最小高度而不是高度 jQuery

javascript - 解释 bindbind() 函数

Php视频上传脚本

javascript - 如何使用 prettify.js 主题?

angularjs - 具有嵌套属性的 ng-table 过滤器

angularjs - 如何在 Angular 测试中重用辅助函数?

javascript - AngularJS - $resource.save 后卡住处理响应(需要 json)

javascript - 尝试使用 jQuery 验证表单字段

javascript - 是否可以制作一个按钮作为文件上传按钮?