将变量传递给UI-bootstrap模式而不使用$ scope

时间:2015-11-18 22:18:47

标签: angularjs controller angularjs-scope angular-ui-bootstrap bootstrap-modal

由于我是使用AngularJS的初学者,$scope方法在不同的控制器之间传递数据(在我的例子中),模态让我发疯。由于这个原因,我在网上搜索并发现了一个有趣的blogpost关于将数据传递到UI-bootstrap模式而不使用$scope

我深入研究了这篇博客文章和交付的plunk,它非常好用,并开始根据自己的需要采用它。

我想要实现的是打开一个提供文本输入的模式,用户可以在其中更改给定产品的描述。由于这不仅仅提供了一个最小的工作示例,我只是将所有内容分解为此plunk中可用的相对较小的代码段。

将数据从主控制器传递到模态似乎可以正常工作,因为默认的产品描述会根据需要显示在模态文本输入中。但是,将数据从模态传回显示index.html中的数据的主控制器似乎不起作用,因为旧的描述在模态中编辑后显示在那里。

总结一下我的两个问题是:

  1. 为了实现“双向约束”,我在做什么是错误的?从主控制器进入模态的文本输入和整个回程,因为相同的方法在提到的博客帖子中工作(好吧,因为博客文章中显示的方法工作,我的代码必定有问题,但我不能发现错误)
  2. 如果仅在单击此按钮并且放弃任何其他情况下的任何更改(单击Accept按钮或关闭模式时),我如何实现正确的Cancel按钮才能接受更改的说明点击旁边的那个)?

1 个答案:

答案 0 :(得分:1)

在您的主控制器中,创建两个解析器功能:getDescriptionsetDescription

在你的模态控制器中,使用它们。

您的模态HTML

<div class="modal-header">
    <h3 class="modal-title">Test Text Input in Modal</h3>
</div>
<div class="modal-body">
    Product description:
    <input type="text" ng-model="modal.description">
</div>
<div class="modal-footer">
    <button ng-click="modal.acceptModal()">Accept</button>
    <button ng-click="modal.$close()">Cancel</button>
</div>

您的主控制器

function MainCtrl($modal) {
  var self = this;
  self.description = "Default product description";

  self.DescriptionModal = function() {
    $modal.open({
      templateUrl: 'modal.html',
      controller: ['$modalInstance', 
                   'getDescription', 
                   'setDescription', 
                    ModalCtrl
                  ],
      controllerAs: 'modal',
      resolve: {
        getDescription: function() {
          return function() { return self.description; };
        },
        setDescription: function() {
          return function(value) { self.description = value; };
        }
      }
    });
  };
};

你的模态控制器

function ModalCtrl($modalInstance, getDescription, setDescription) {
  var self = this;
  this.description = getDescription();

  this.acceptModal = function() {
    setDescription(self.description);
    $modalInstance.close();
  };
}