【问题标题】:Pass variable to UI-bootstrap modal without using $scope在不使用 $scope 的情况下将变量传递给 UI-bootstrap 模式
【发布时间】:2015-11-18 22:18:47
【问题描述】:

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

我深入了解了这篇博文和提供的 plunk,它工作得非常好,并开始根据自己的需要采用它。

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

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

总结我的两个问题是:

  1. 为了实现从主控制器到模态文本输入的“双向绑定”以及整个返回过程,我做错了什么,因为在提到的博文中使用了相同的方法(好吧,如所示的方法在博文作品中,我的代码一定有问题,但我找不到错误)
  2. 如何实现正确的Accept 按钮,以便仅在单击此按钮时接受更改的描述,并在任何其他情况下放弃任何更改(单击Cancel 按钮或单击旁边的关闭模式)?

【问题讨论】:

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


    【解决方案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();
      };
    }
    

    【讨论】:

    • 我刚刚在这个plunk总结了你的代码sn-ps
    • 不错。我喜欢@albert 添加closeModal 函数以使他的modal.html 更具表现力。
    • 额外问题:如何修改 getDescriptionsetDescription 函数以检索和更新 MainCtrl 中的任何内容?
    • 我们真的不想为每个新的模型元素添加两个函数。我们需要像retrieve(description)update(description,value) 这样的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多