如何在AngularJS Bootstrap模式中从AJAX调用加载JSON数据

How to load JSON data from an AJAX call in AngularJS Bootstrap modal

本文关键字:调用 AJAX 加载 JSON 数据 AngularJS Bootstrap 模式      更新时间:2023-09-26

我想创建以下内容。有一个按钮,当点击该按钮时,将从Angular Bootstrap[1打开一个对话框/模式,然后当应用程序从服务器获取json数据时,该对话框将显示一个加载指示符,然后将该数据显示在对话框内容中。

我想我会制作一个对话框模板,其中包含json数据的解析代码,即一些ng重复,例如将其显示为列表。

我不清楚:

  1. 在这个过程中,我在哪里添加负载指示器(比如spin.js)。我希望能够从我假设的控制器中引用对话框模板中的一些div
  2. 我在什么时候进行ajax调用
  3. 如何将数据传递给模板并对其进行解析

无需手动将模板加载到对话框中。AngularUI的$dialog服务接受静态模板或模板url。该URL可以返回任何内容,它只需通过AJAX调用执行GET请求,并用返回的任何数据填充对话框。该请求被缓存在本地,因此下一次调用应该比第一次更快。

这里有一个简单的片段让你开始:

Javascript

angular.module('app', ['ui.bootstrap.dialog'])
    .controller('Ctrl', function($scope, $dialog, $window) {
        $scope.open = function() {
            var options = {
                backdrop: true,
                keyboard: true,                    
                controller: 'DialogCtrl', // the dialog object will be inject 
                                          // into it
                templateUrl: 'path/to/view' // can be either a static file or 
                                            // a service that returns some data
            };
            var dialog = $dialog.dialog(options);
            dialog.open().then(function(result) {
                if (result === 0) {
                    $window.alert("Cancel pressed");
                }
                else if (result === 1) {
                    $window.alert("OK pressed");
                }
            });
        };
    })
    .controller('DialogCtrl', function($scope, $http, dialog) {
        // Here you can put whatever behavior the dialog might have
        $scope.close = function(result) {
            dialog.close(result);
        };
        // Loads some data into the dialog scope
        $http.get('/path/to/service')
            .success(function(response) {
                $scope.items = response;
            });
    });

主HTML

<div ng-app="app" ng-controller="Ctrl">
  <button ng-click="open()">Open dialog</button>
</div>

查看HTML

<div class="modal-header">
  <h3>Title</h3>
</div>
<div class="modal-body">
  <!-- Renders the data loaded by the controller -->
  <p ng-repeat="item in items">{{ item }}</p>
</div>
<div class="modal-footer">
  <button class="btn" ng-click="close(0)">Cancel</button>
  <button class="btn btn-primary" ng-click="close(1)">OK</button>
</div>

这个Plunker脚本演示了以上所有内容。

Update:我更新了示例代码,以演示如何动态更改对话框内容。

"modal是一个指令,它重用$dialog服务来提供简单的创建已经在DOM中的模态,而无需创建局部视图和控制器。

该指令共享$dialog全局选项。"

检查以下引导对话框选项的url:

http://angular-ui.github.io/bootstrap/#/dialog