ng-controller在html中不起作用

时间:2015-04-21 10:30:10

标签: angularjs angularjs-directive ng-bind-html

您好我收到的HTML响应中嵌入了完整的角度代码,我尝试了ng-bind-html和ng-html-compile进行渲染。它们都不起作用.HTML元素正在正确呈现,但没有任何ng指令正常工作。有人可以帮忙解决这个问题吗?

在我的控制器内部,我将http响应数据(html)分配到rootscope变量($ rootScope.htmlResponse = data)。

这是html编译的指令

.directive('ngHtmlCompile', function($compile) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        scope.$watch(attrs.ngHtmlCompile, function(newValue, oldValue) {
            element.html(newValue);
            $compile(element.contents())(scope);
        });
    }
};
})

searchResults.html:

<ion-view  ng-swipe-left="scanClick()">
<ion-nav-buttons side="left">
    <button class="button button-icon button-dark ion-navicon" menu-toggle="left" style="margin-left:-10px;margin-right:-20px" id="lhm_button">
    </button>

</ion-nav-buttons>
<ion-nav-title>
    Product Detail
</ion-nav-title>
<ion-nav-buttons side="right">
    <button class="button button-icon button-dark ion-search" ng-click="searchIconClick()" style="margin-top:4px;background:#8eb4e3;line-height:5px"></button>
</ion-nav-buttons>
<ion-content>

<div>
    <p **ng-html-compile="htmlResponse"**></p>
</div>
</ion-content>

</ion-view>

以下是我得到的http响应示例:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js">    </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular-animate.min.js"></script> 
 </head>
 <body ng-app="myapp">
 <div ng-controller="myController">
  {{name.myname}}
 </div>

 <script>
 var app = angular.module('myapp', []);
 app.controller('myController', function ($scope) {
 $scope.name={};
 $scope.name.myname = "stack";
 });

 </script> 
 </body>
 </html>

显示以下结果:

 {{name.myname}}

2 个答案:

答案 0 :(得分:1)

尝试使用iframe ....

<iframe width="100%" height="500px" ng-attr-srcdoc="{{htmlResponse}}"></iframe>

答案 1 :(得分:-2)

获取此示例代码 试试这段代码

<!DOCTYPE html>
 <html>
  <head>
    <meta charset="utf-8" />
    <title>TEST</title>
    <script src="angular.js"></script> 
 </head>
 <body ng-app="myapp">
 <div ng-controller="myController">
   {{name}}
 <mydir rootdata="htmlresponse"></mydir>
 </div>

 <script>
 var app = angular.module('myapp', []);
 app.controller('myController', function ($scope,$rootScope) {
  $scope.name = "stack";
  $rootScope.htmlresponse = "I am root scope";
 });
 app.directive("mydir", function () {
  return {
          restrict : 'E',
          scope    : {
                         da : "=rootdata";
                     }
          template : "<div>Hello I am Directive {{da}}</div>"
         }
 });

 </script> 
</body>
</html>