AJS自定义html以仅显示ng-include

时间:2019-02-26 03:05:27

标签: angularjs angularjs-directive angularjs-include

我能够将html文件包含到我的有角度的应用程序(包括ng-include)中,但我不希望html中的所有内容都显示在我的应用程序中(这不是有角度的应用程序,其内容不能进行更改。因此ng-show和ng-hide无效)

下面是示例代码

<div ng-app="myApp" ng-controller="customersCtrl"> 
  <div ng-include="'myTable.htm'"></div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {

});
</script>

myTable.htm

<html>
  <head>this is head</head>
  <body>
<div> test
<h1 id="needToDispalythis">ds,<span>something</span></h1>
</div></body>
</html>

在这里,我只需要显示ID为 needToDispalythis 的内容。我尝试使用指令,但无法实现。任何帮助或指针

1 个答案:

答案 0 :(得分:0)

更新

您可以简单地使用jQuery隐藏ID为 needToDisplayThis 的元素之外的其他元素,如下所示:

$(document).ready(function(){
  var elemToShow = $('#needToDisplayThis');
  $('body').html('<div><h1>'+elemToShow.html()+'</h1></div>');
});

首先,您的 ng-include myTable.html 不应包含<html><head></head><body></body></html>标记。仅使用您要呈现的标记,即:<div> test<h1 id="needToDispalythis">ds,<span>something</span></h1></div>

所以您的主要html应该如下所示:

<html>
  <head>this is head</head>
  <body>
    <div ng-app="myApp" ng-controller="customersCtrl"> 
      <div ng-include="'myTable.htm'"></div>
    </div>

    <script>
      var app = angular.module('myApp', []);
      app.controller('customersCtrl', function($scope, $http) {

      });
    </script>
  </body>
</html>

并且您包含的html应该如下所示:

<div> 
  <span>test</span>
  <h1 id="needToDispalythis">ds,<span>something</span></h1>
</div>

现在只显示<h1>元素,您需要隐藏<span>元素,因此在其中添加一个ng-hide属性:

<span ng-hide="hideThis">test<span/>

现在只需将$scope上的hideThis变量设置为true:

<script>
   var app = angular.module('myApp', []);
   app.controller('customersCtrl', function($scope, $http) {
     $scope.hideThis = true;
   });
</script>

最后,您的主要html如下所示:

<html>
  <head>this is head</head>
  <body>
    <div ng-app="myApp" ng-controller="customersCtrl"> 
      <div ng-include="'myTable.htm'"></div>
    </div>

    <script>
      var app = angular.module('myApp', []);
      app.controller('customersCtrl', function($scope, $http) {
        $scope.hideThis = true;
      });
    </script>
  </body>
</html>

和您的myTable.html看起来像这样:

<div> 
  <span ng-hide="hideThis">test<span/>
  <h1>ds,<span>something</span></h1>
</div>