如何使用Angular UI Bootstrap Modal在AngularJS中获取$ Scope的字段

时间:2014-07-21 13:17:12

标签: javascript angularjs angular-ui angular-ui-bootstrap

modalLoginController.js

    angular.module('App')
  .controller('modalLoginController', function ($modal, $scope, loginService) {

  $scope.userName = null;
  $scope.userPassword = null;

  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'modalLogin.html',
      controller: ModalInstanceCtrl,
      size: size,
      resolve: {
        loginDto: function() {
          var login = {};
          login.userName = $scope.userName;
          login.userPassword = $scope.userPassword;

          return login;
        }
      }
    });
  };

  var ModalInstanceCtrl = function ($scope, $modalInstance, $window, loginDto) {

    $scope.ok = function () {
      var login = {};
      login.userName = $scope.userName;
      login.userPassword = $scope.userPassword;

      $window.alert(login.userName + ' ' + login.userPassword);

      var response = loginService.validateLogin(loginDto);
      if (response.success) {
        $modalInstance.close();
      } else {
        $window.alert('zebrero');
      }
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };

  };

});

的index.html

    ...
...
...
<script type="text/ng-template" id="modalLogin.html">
    <div class="modal-header">
        <h3 class="modal-title">Login</h3>
    </div>
    <div class="modal-body">
        <input type="text" ng-model="userName" placeholder="user"/>
        <input type="password" ng-model="userPassword" placeholder="password"/>
    </div>
    <div class="modal-footer">
        <button class="btn btn-default" ng-click="ok()">Login</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
    </div>
    <div class="modal-body" ng-show="isLogged">
        <label>Usuário Logado</label>
    </div>
</script>

</head>
<body ng-controller="MainCtrl">  
...
...
...
    <div id="loginLogout" ng-controller="modalLoginController">
        <button  class="btn btn-default" ng-click="open('sm')" modalLogin ng-show="!isLogged" >Login</button>
    </div>
...
...
...

为什么我无法获得ModalInstanceCtrl中定义的$ scope.userName和$ scope.userPassword,即使我可以使用$ scope.ok和$ scope.cancel? 仅针对文本,我将$ scope.userName和$ scope.userPassword放在解析中作为 loginDto ,但是也不起作用。< / p>

1 个答案:

答案 0 :(得分:1)

模态控制器具有自己的范围。您还没有在其中定义$scope.username

您需要从注入的loginDto对象访问这些内容。

尝试:

$scope.userName = loginDto.userName;