【问题标题】:Angular UI Modal opened promise is resolved before modal is shownAngular UI Modal 打开的承诺在显示模态之前解决
【发布时间】:2014-06-27 21:08:23
【问题描述】:

我正在尝试在打开的模式上执行一个 jQuery 脚本,以便将其中一个字段转换为 jQuery UI Spinner

我正在使用Angular UI 中记录的opened 承诺。

问题: jQuery 选择器没有按预期工作,并且不检索任何内容。

所以我的控制器的功能之一是这样的:

var modalInstance = $modal.open({
    templateUrl: 'modalDialog.html',
    controller: modalCtrl,
    resolve: {
        noOfItems: function(){
            return $scope.noOfItems;
        }
    }
});

modalInstance.opened
    .then(function () {
        $(".spinner").spinner({
            max: 20,
            min: 1
        });
    });

modalInstance.result
    .then(function () {
        console.log("modal closed");
    });

还有我的 HTML:

<script type="text/ng-template" id="modalDialog.html">
    <div class="modal-header">
        <h4 class="modal-title">My Modal</h4>
    </div>
    <div class="modal-body">
        <input class="form-control spinner" type="text" ng-model="noOfItems" />
    </div>
    <div class="modal-footer">
        <button class="btn btn-default" ng-click="cancel()">Cancel</button>
        <button class="btn btn-primary" ng-click="save()">Save</button>
    </div>
</script>

modalCtrl 无关紧要。

提示: 我尝试在调用opened 承诺时将debugger 放在正确的位置,发现模态尚未打开。

仅供参考,我正在使用 jQuery 1.9.0、jQuery UI 1.10.4、AngularJS 1.2.16 和 Angular UI Bootstrap v0.11。

【问题讨论】:

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


    【解决方案1】:

    您从错误的角度处理问题,试图从控制器进行低级 DOM 操作。这在 AngularJS 世界中是一个很大的禁忌,你会在路上遇到各种各样的麻烦。

    您的 UI 逻辑不应“等待”将给定 DOM 节点添加到 DOM 树中,而应以声明方式表示。在这种特殊情况下,这意味着您应该编写一个“滑块”指令,就像这样简单:

    yourModule.directive('mySpinner', function() {
      return {
        link: function(scope, elm) {
          elm.spinner({
            max: 20,
            min: 1
          });
        }
      };
    });
    

    然后在模态的 HTML 内使用这个新定义的指令:

    <input class="form-control spinner" type="text" my-spinner ng-model="noOfItems"/>
    

    这样,当模态的内容被添加到 DOM 时,您无需担心并且您已经使自己喜欢使用可重用的方式来定义微调器!

    回到与 $modal 相关的问题 - 当所有数据准备好并且模式即将显示(动画开始等)以能够显示等待指示符或类似内容时,opened 承诺已解决。绝不像 AngularJS 那样,它被设计为知道模态的内容何时被插入到 DOM 树中。大部分时间并不真正需要这种知识。

    【讨论】:

    • 谢谢,我是 AngularJS 的新手,有时需要提醒一下它的最佳实践。
    猜你喜欢
    • 2015-06-24
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2018-08-16
    • 2015-06-23
    相关资源
    最近更新 更多