Подтвердить что ты не робот

Проблема в AngularJS с использованием AngularUI Bootstrap Modal

plunker: http://plnkr.co/edit/wURNg8ByPYbEuQSL4xwg

example.js:

angular.module('plunker', ['ui.bootstrap']);
  var ModalDemoCtrl = function ($scope, $modal) {

  $scope.open = function () {
    var modalInstance = $modal.open({
      templateUrl: 'modal.html',
      controller: 'ModalInstanceCtrl'
    });
  };
};

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

  $scope.ok = function () {
    alert($scope.text);
  };

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

index.html

<!doctype html>
<html ng-app="plunker">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
  </head>
  <body>

  <div ng-controller="ModalDemoCtrl">
    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
  </div>
 </body>
</html>

modal.html:

<div class="modal-header">
    <h3>I'm a modal!</h3>
</div>
<textarea ng-model="text"></textarea>
<div class="modal-footer">
    <button class="btn btn-primary" ng-click="ok()">OK</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

Почему я не могу получить $scope.text, определенный в ModalInstanceCtrl, хотя я могу использовать $scope.ok и $scope.cancel?

4b9b3361

Ответ 1

Похож на проблему с областью. Я получил его, чтобы он работал следующим образом:

var ModalInstanceCtrl = function ($scope, $modalInstance) {
    $scope.input = {};
    $scope.ok = function () {
        alert($scope.input.abc);
    };

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

HTML:

<textarea ng-model="input.abc"></textarea>

Ответ 2

Обновление Nov 2014: проблема исправлена ​​с помощью angular -ui-bootstrap 0.12.0 - область трансключений объединяется с областью контроллера. Нет необходимости ничего делать. Просто оставайтесь с:

<textarea ng-model="text"></textarea>

До 0.12.0:

Angular -UI-модалы используют переход для прикрепления модального контента, что означает, что любые новые записи области видимости, сделанные в модальном, создаются в области содержимого.

Вы должны использовать наследование и инициализировать пустую запись text в родительском $scope или вы можете явно привязать вход к родительской области:

<textarea ng-model="$parent.text"></textarea>

Ответ 3

Давайте попробуем объяснить причину. ui-bootstrap modal sourcecode:

.directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
  restrict: 'EA',
  scope: {
    index: '@',
    animate: '='
  },
  replace: true,
  transclude: true,
  templateUrl: function(tElement, tAttrs) {
    return tAttrs.templateUrl || 'template/modal/window.html';
  },

и шаблон sourcecode - window.html:

<div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}" ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)">
<div class="modal-dialog" ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"><div class="modal-content" modal-transclude></div></div>

существует директива modal-transclude, содержимое вашего диалогового окна будет вставляться в нее, это исходный код:

.directive('modalTransclude', function () {
return {
  link: function($scope, $element, $attrs, controller, $transclude) {
    $transclude($scope.$parent, function(clone) {
      $element.empty();
      $element.append(clone);
    });
  }
};

})

теперь взгляните на официальный документ $compile:

Transclusion Functions

When a directive requests transclusion, the compiler extracts its contents and provides 
a transclusion function to the directive link function and controller. 
This transclusion function is a special linking function that will return the compiled 
contents linked to a **new transclusion scope.**

transclude создаст новую область видимости контроллера