每次使用Angular UI.Bootstrap打开全新的$ modal

时间:2016-07-22 06:42:30

标签: angularjs asp.net-mvc angular-ui-bootstrap

我使用AngularJS和ui.bootstrap并且有一个模态指令,它可以正常工作。

myApp.directive("modalButton", ['$uibModal', function ($uibModal) {
    return {
        restrict: "A",
        scope: {
            modalUrl: '@',
            modalModel: '='
        },
        link: function (scope, element, attrs) {
            element.bind('click', function () {
                var modalInstance = $uibModal.open({
                    templateUrl: scope.modalUrl, // Here I want to use an url instead.
                    controller: 'editDeliveryCtrl as ctrl',
                    resolve: {
                        model: function () {
                            return scope.modalModel;
                        }
                    }
                });
            });
        }
    };
}]);

并使用如下:

<button type="button" class="btn btn-xs btn-default" modal-model="ctrl.currentDelivery" modal-button modal-url="@Url.Action("AddDelivery", "ProvisionContract", new {provisionContractId = Model.Id})">
    <span class="fa fa-plus" area-hidden="true"></span>
</button>

当用户点击带有指令的按钮时,会显示模态。但是,我使用MVC.Net并且我加载的模式通常是具有@Html.AntiForgeryToken()或其他代码隐藏逻辑的形式。所以我真正想要的是每次重新加载模板(向服务器发出新请求)。

我已经阅读了下面的问题,这可能是一个很好的答案,但我真正想要的是根本不使用模板。我希望$uibModal将其加载为全新的HTML。

How to remove angular $modal cache?

我可以让$uibModal每次都重新加载模板作为全新的HTML吗?更像是jQuery中的$.load

1 个答案:

答案 0 :(得分:1)

您在Angular应用中加载的所有模板都存储在$templateCache中,因此下次您引用它们时不会下载它们。

在您的情况下,这不是理想的行为,因为同一网址的HTML内容可能会随着时间的推移而发生变化。

因此,在使用

打开模式之前,必须从缓存中删除缓存的URL
$templateCache.remove(scope.modalUrl);

另请参阅How to remove angular $modal cache

另一个想法是覆盖$templateCache的put方法,因此它不会存储某些特定的路径。

angular.module('yourApp').decorator('$templateCache', function($delegate) {
  var originalPut = $delegate.put;
  $delegate.put = function (templatePath, contents) {
    // specifiy conditions which would tell what paths should not be cached
    if (templatePath == '/this-should-not-be-cached.html' || templatePath.match(/some-regex/)) {
      return;
    }
    else {
      originalPut(templatePath, contents);
    }
  };
  return $delegate;
}); 

您无法禁用$templateCache,因为许多图书馆使用它来存储随附的模板(例如ui-bootstrap等)。