【问题标题】:AngularJS scope is not available when using Bootstrap Validation Plugin使用引导验证插件时,AngularJS 范围不可用
【发布时间】:2017-10-24 06:14:19
【问题描述】:

我正在尝试将此插件与 angularjs 一起使用来验证表单 http://1000hz.github.io/bootstrap-validator/plugimg

我已经尝试了很多,但我不知道为什么在插件提交方法中无法访问范围变量。希望有人可以帮助我!

这是控制器

 app.controller('LoginController', function($scope,$http,$localStorage) {

      //initialize plugin on controller load
      $('#loginform').validator();

      //gets called on form submit
      $('#loginform').validator().on('submit', function (e) {

        //below line says : if there are no errors then coninue
        if (!e.isDefaultPrevented()) {
            $http.post('api/user/login',{
                email: $scope.email, // is undefine
                password: $scope.password // is undefined
            }).then(function successCallback(response) {
                $localStorage.isLoggedIn = 1;
            }, function errorCallback(response) {

            });
        }

        //prevent form submit
        return false;

      });

  });

HTML

<div class="container" ng-controller="LoginController">

  <form class="form-horizontal" novalidate id="loginform">

    <div class="form-group">

      <label for="email" class="col-md-4 control-label">E-Mail ID</label>
      <div class="col-md-6">
        <input id="email" type="email" class="form-control" name="email" ng-model="email" required> </div>
    </div>

    <div class="form-group">
      <label for="password" class="col-md-4 control-label">Password</label>

      <div class="col-md-6">
        <input id="password" type="password" class="form-control" name="password" ng-model="password" required>

      </div>
      </div>


      <div class="form-group">
        <div class="col-md-6 col-md-offset-4">
          <button class="btn btn-primary">
            <i class="fa fa-btn fa-sign-in"></i> Login
          </button>

        </div>
      </div>

  </form>
  </div>

【问题讨论】:

  • 不建议在 Angular 代码中编写 jquery 代码;角度代码使用自己的角度上下文;所以你总是会担心你的代码在哪个上下文中。我建议你只使用 ng + bootstrap 。您可以使用 jquery 进行的所有验证也可以在 Angular 中完成。另外,您始终处于角度上下文中。
  • 还可以查看 Angular 包 ng-messages,它可以完成显示验证消息的工作。请记住,Angular 是一个框架,与与该框架一起工作的框架事物一起使用总是好的。
  • 有没有我们可以在不删除 jquery 插件的情况下使这段代码工作?
  • 你想以错误的方式做吗?这是浪费时间。

标签: jquery angularjs angularjs-scope


【解决方案1】:

当提交事件被触发时,$scope.email$scope.password 的值将是未定义的,因为您创建了一个在 angulars 控制之外执行的事件(在使脏检查成为可能的摘要循环之外)。

解决办法是去掉jQuery代码,只使用角度代码。

【讨论】:

猜你喜欢
  • 2014-09-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
相关资源
最近更新 更多