ng-include not working with script type=“text/ng-template”

前端 未结 3 1367
长发绾君心
长发绾君心 2020-12-30 06:55

Here is my Plunker:

http://plnkr.co/edit/oIei6gAU1Bxpo8VUIswt

When the button is clicked, the following should be inserted before the \"Hello World!\" span:<

相关标签:
3条回答
  • 2020-12-30 07:12

    Simply your script :

    <script type="text/ng-template" id="tempTest">
      <div>
        <span>Properly Inserted</span> 
      </div>
    </script>
    

    Must be inside the MainCtrl controller selector like this :

    <div ng-app="plunker" ng-controller="MainCtrl">
    <script type="text/ng-template" id="tempTest">
    <div>
    <span>Properly Inserted</span> 
    </div>
    </script>
    </div>
    
    0 讨论(0)
  • 2020-12-30 07:14

    The quick answer might have been:

    <div ng-include="'tempTest'"></div>
    Probably you just forgot the single quotes to reference the template.

    The long answer:

    It is not advised to access the DOM inside a controller - you will get in trouble as the code will be flooded with $scope.$apply() calls. Think about implementing this feature with a directive. I tried to create a starting point from your code here

    http://plnkr.co/UWUCqWuB9d1dn6Zwy3J3

    var app = angular.module('plunker', ['ngAnimate']);
    
    app.directive('greeting', function($compile){
      return {
        restrict: 'E',
        scope: {
          name: '='
        },
        template: '<div>'+
                  '  <span>Hello {{name}}!</span>'+
                  '  <button ng-click="insert()">test</button>'+
                  '</div>',
        link: function(scope, element, attrs) {
           scope.insert = function() {
             var container = angular.element('<div ng-include="\'tempTest.html\'"></div>');
             element.before($compile(container)(scope));
           }
        }
      }
    })
    
    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
    });
    
    <greeting name="name"></greeting>
    

    The template elements are inserted before the Hello World! textnode everytime the button is clicked.

    Side note You dont even need the scope{ name: '='} as the directive will inherit its surrounding scope, but its the cleaner way to pass (actually bind) controller variables to a directive explicitly.

    0 讨论(0)
  • 2020-12-30 07:25
    <div ng-include src="tempTest"></div> 
    

    This should work

    ^^^ note that this will NOT even begin to work unless single quotes are added (as @JHixson has already pointed out), like so:

    <div ng-include src="'tempTest'"></div>
    
    0 讨论(0)
提交回复
热议问题