javascript - 将模板包含到特定 div

标签 javascript html angularjs

我想加载特定 div 标签的脚本模板。 在我的演示中,我有 3 个“显示”链接。如果我单击任一显示链接,它将加载所有“显示”链接的脚本。但我只想加载我单击的“显示”链接的脚本。

请参阅PLUNKER .

(function(angular) {
  'use strict';
angular.module('docsTemplateUrlDirective', [])
  .controller('Controller', ['$scope', '$compile', function($scope, $compile) {
    
    $scope.showdiv = function(){
      $scope.templateURL = 'my-tmpl';
    
    };
  }]);
})(window.angular);
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8" />
    <title>Example - example-example12-production</title>
    <script data-require="jquery@2.1.1" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="docsTemplateUrlDirective" data-ng-init="names=['1','2','3']">
    <div ng-controller="Controller">
       <script type="text/ng-template" id="my-tmpl">
         <p>Hello</p>
       </script>
      <div data-ng-repeat="x in names"> 
      <a href="#" ng-click="showdiv()">show</a>
      <div id="d">
        
        <div ng-include=templateURL></div>
        
        
      </div>
      </div>
    </div>
  </body>

</html>

最佳答案

If you need to show same things means need to use same template then use the following code.

这里我定义了一个新的作用域变量。 看看更新的plunker

(function(angular) {
  'use strict';
angular.module('docsTemplateUrlDirective', [])
  .controller('Controller', ['$scope', '$compile', function($scope, $compile) {
    
    $scope.a = 0; //Here
    $scope.showdiv = function(x){
      $scope.templateURL = 'my-tmpl';
      $scope.a = x; //and Here
    };
  }]);
})(window.angular);
 <a href="#" ng-click="showdiv(x)">show</a> <!-- pass x to remember --> 
 <div id="d"  ng-show="a==x"> <!--and check that new variable set as x or not -->
   <div ng-include="templateURL"></div>
  </div>

关于javascript - 将模板包含到特定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34281712/

相关文章:

javascript - 如何检测浏览器强制刷新事件 - 跨浏览器

javascript - 如何返回上一页,但不计算js中的url变量

javascript - Google 面积图中重复的一系列数据

javascript - 如何在打开另一个div的同时关闭div

c# - 我的按钮没有回发?我将它与 Javascript 绑定(bind)在一起,而 Javascript 又与 div 绑定(bind)在一起

javascript - AngularJS 和异步调用

javascript - AngularJS : Adding variable into a chain of promises

javascript - 在 Javascript 中使用 Django 变量与 Google API 一起使用

html - 为什么 flex 元素的宽度和高度会影响 flex 元素的呈现方式?

javascript - 将 $scope 对象传递给路由,如果刷新则保留