【问题标题】:Angular js scope between directive and controllers指令和控制器之间的Angular js范围
【发布时间】:2015-02-13 07:42:09
【问题描述】:

我必须在弹出窗口中显示用户登录页面,并且必须使用 Angular js 在服务器上验证用户名和密码。我创建了一个应用模型文件、一个控制器、一个服务和一个指令。我的代码如下所示,

app.js

angular.module('mint', ['ngAnimate', 'toastr']);

mycontroller.js

angular.module('mint').controller(
        'headercontroller',
        [
                '$scope',
                'headerservice',
                'toastr',
                function($scope, headerservice, toastr) {
$scope.showModal = false;

                    $scope.toggleModal = function() { 
                        $scope.showModal = !$scope.showModal;
                    };
$scope.userSignin = function(){
                        $scope.userloginbtn = false;
                        if($scope.signin_form.$valid){  //Error on this line signin_form is undefine. using $valid for undefine
                            var record = {};
                            angular.extend(record, $scope.signinForm);
                            console.log(record);
                        }else {
                            $scope.signin_form.submitted = false;
                            $scope.userloginbtn = true;
                        }
                    };
} ]);

我的directive.js 文件是

angular
        .module('mint')
        .directive(
                'modal',
                function() {
                    return {
                        template : '<div class="modal fade">'
                                + '<div class="modal-dialog">'
                                + '<div class="modal-content">'
                                + '<div class="modal-header">'
                                + '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
                                + '<h4 class="modal-title"><span><i class="fa fa-user"></i> {{ title }}</span></h4>'
                                + '</div>'
                                + '<div class="modal-body" ng-transclude></div>'
                                + '</div>' + '</div>' + '</div>',
                        restrict : 'E',
                        transclude : true,
                        replace : true,
                        scope : true,
                        link : function postLink(scope, element, attrs) {
                            scope.title = attrs.title;

                            scope.$watch(attrs.visible, function(value) { 
                                if (value == true)
                                    $(element).modal('show');
                                else
                                    $(element).modal('hide');
                            });

                            $(element).on('shown.bs.modal', function() {
                                scope.$apply(function() {
                                    scope.$parent[attrs.visible] = true;
                                });
                            });

                            $(element).on('hidden.bs.modal', function() {
                                scope.$apply(function() {
                                    scope.$parent[attrs.visible] = false;
                                });
                            });
                        }
                    };
                });

我的 html 文件看起来像

<!DOCTYPE html>
<html lang="en" ng-app="mintmygold">
<body>
    <div class="container-fluid ban_bg"
        ng-controller="headercontroller">
        <div class="but_bg">
                    <button type="button" class="btn btn-default btn_sin" ng-click="toggleModal()">
                        <span><i class="fa fa-key"></i> Sign In</span>
                    </button>
        </div>

        <modal title="Login" visible="showModal">
                <form role="form" name="signin_form" class="signup_form" novalidate
                    ng-model="signin_form">
                    <div class="form-group">
                        <p class="infoMsg" ng-model="signinform_info">Please fill in your login credentials:</p>
                    </div>
                  <div class="form-group">
                    <label for="email">Email address</label>
                    <input ng-model="signinForm.userEmail" name="userEmail" type="email" class="form-control" id="email" placeholder="Enter email" required />
                    <div
                                ng-show="signin_form.$submitted || signin_form.userEmail.$touched">
                                <span ng-show="signin_form.userEmail.$error.required">Enter your
                                    email.</span> <span ng-show="signin_form.userEmail.$error.email">This
                                    is not a valid email.</span>
                            </div>
                  </div>
                  <div class="form-group">
                    <label for="password">Password</label>
                    <input ng-model="signinForm.userPassword" name="userPassword" type="password" class="form-control" id="password" placeholder="Password" required />
                    <div
                                ng-show="signin_form.$submitted || signin_form.userPassword.$touched">
                                <span ng-show="signin_form.userPassword.$error.required">Enter your
                                    password.</span>
                            </div>
                  </div>
                  <button ng-disabled="signin_form.$invalid || !userloginbtn" ng-model="signin" ng-click="userSignin()" type="submit" class="btn btn-primary">Submit</button>
                </form>
              </modal>
        </div></body></html>

现在我可以在单击登录按钮时显示弹出窗口。当我提交表单时,我无法从控制器中的弹出表单中获取电子邮件值和密码值。我使用范围的错误是什么。请任何人帮助我。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    快速忽略,这似乎是一个愚蠢的错误。换行

    来自

    angular.module('mint', ['ngAnimate', 'toastr']);
    

    angular.module('mintmygold', ['ngAnimate', 'toastr']);
    

    【讨论】:

      【解决方案2】:

      您正在使用 scope: true ,这意味着您的指令正在创建一个子范围并从其父范围继承属性。 因此,您在指令范围内定义的任何属性都不存在于您的控制器范围内。

      更改表单名称=signin_form for form name=$parent.signin_form or scope: false 应该可以解决问题

      不过,我没有对此进行测试。这不是一个好的解决方案。 我可能会创建一个服务来启动弹出窗口并返回一个相应地解决/拒绝的承诺。

      app.js

      var app = angular.module('plunker', []);
      app.controller('MainCtrl', function($scope, modal) {
        $scope.launch = function(){
          modal.show().then(function(user){
            console.log(user)
          }, function(err){
            console.log(err)
          });  
        }
      
      
      });
      
      app.factory('modal', ["$document", "$compile", "$rootScope", "$templateCache", "$timeout", "$q",
        function ($document, $compile, $rootScope, $templateCache, $timeout, $q) {
          var $body = $document.find('body');
      
          return {
            show: function(){
              var defer = $q.defer(),
                  child = $rootScope.$new();
      
              child.user = {};
      
              child.close = function(){
                defer.reject('canceled');
                tpl.remove();
              }
      
              child.submit = function(){
                defer.resolve(child.user);
                tpl.remove();
              }
      
              var tpl = angular.element($templateCache.get('modal.html'));
              $compile(tpl)(child);
              $body.append(tpl);
      
              return defer.promise;
            }
          };
      
      }]);
      

      index.html

      <script type="text/ng-template" id="modal.html">
          <div class="modal in" style="position: static; display: block">
            <div class="modal-dialog">
              <form ng-submit="submit()" class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" ng-click="close()" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                  <h4 class="modal-title">Modal title</h4>
                </div>
      
                <div class="modal-body">
                    Email: <input ng-model="user.email"></input><br>
                    Password: <input ng-model="user.password"></input>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" ng-click="close()">Close</button>
                  <button type="submit" class="btn btn-primary">Sign in</button>
                </div>
              </form>
            </div>
          </div>
      </script>
      <button type="button" ng-click="launch()" class="btn btn-primary">Show modal</button>
      

      Plunker

      这只是一个概念证明。我认为足以让你开始。我强烈建议您查看UI Bootstrap 以及实现其模态的方式

      【讨论】:

      • 我用 $parent.signin_form 更改了表单名称检查了它现在正在工作。非常感谢。能否请您使用弹出式服务将链接发送给我
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多