AngularJS Modal not showing up when templateUrl ch

2020-03-07 09:50发布

问题:

So far, what I have is straight off the Angular UI example:

Controller:

var ModalDemoCtrl = function ($scope, $modal) {

  $scope.open = function () {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl
    });
  };
};


var ModalInstanceCtrl = function ($scope, $modalInstance) {

  $scope.close = function () {
    $modalInstance.dismiss('cancel');
  };
};

And this section, which is just in sitting in the .html for the whole page this modal is on. Html:

<script type="text/ng-template" id="myModalContent.html">
  <div class="modal-header">
    <h3 class="modal-title">I'm a modal!</h3>
    <button class="btn btn-warning" ng-click="close()">X</button>
  </div>
  <div class="modal-body">
    Stuff
  </div>
</script>

This works just fine. But I'm trying to refactor some things out and organize my code, so I would like to move the modal html to its own file. When I do so, and try to use it as by changing the templateUrl to the path: \tmpl\myModalContent.html, it doesn't show up. The backdrop still appears and inspecting the page shows that it loaded correctly, but just won't show up.

I've tried changing the css for the modal per these suggestions with no difference.

My question is, why does this work fine if the script tag is in the main html, but not at all if it is in it's own file?

Here is a plnkr that shows what I mean. If you copy what is in the template.html and place it right above the button in the index.html file, it works...

回答1:

Remove template declaration for template.html and just put raw HTML in there like this:

<!--script type="text/ng-template" id="template.html"-->
            <div class="modal-body">
                 Hello
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" ng-click="cancel()">OK</button>
            </div>
<!--/script-->

Your plnkr worked fine with second click to the button. It'd show the modal as expected. The reason it showed up with second click is because Angular would load up the 'uncompiled' template the first time, then it compiled the template to raw HTML which is ready for your subsequent clicks.

EDIT: Also, when you put the template code right in index.html, Angular compiles the template during its initial pass through the DOM; that's why the modal seemed to work.



回答2:

Well I am clearly a dummy. All I had to do was include my new file in the main view.

<div ng-include="'path-to-file.html'"></div>

Then calling it from the controller was easy, all I needed was the id (modalContent.html) as the templateUrl.

Just keep swimming, and you'll eventually get there :)