2014-10-20 103 views
1

我正在尝试构建动态HTML字符串,其中包含对作用域变量中的更改作出反应的指令。如果我静态构建字符串,那么我的$watch可以正常工作,但如果字符串是动态的,那么$watch不会触发。AngularJS:在动态HTML中使用指令

我相信答案在于使用$compile,我研究了很多例子,但我似乎无法让它们适合我的特定需求。

这可能吗?

我的plunkr,它演示了用上标标记引用句子。

的index.html

<body ng-controller="MainCtrl"> 
    <h3>Static Example</h3> 
    <div>Humpty Dumpty sat<ref><sup>1</sup></ref> on a wall.</div> 
    <div>Humpty Dumpty had a great<ref><sup>2</sup></ref> fall.</div> 

    <h3>Dynamic Example</h3> 
    <div ng-repeat="item in dynamic"> 
     <span ng-bind-html="item | to_trusted"></span> 
    </div> 
    <br> 
    <input type="checkbox" ng-click="sup = !sup"> hide/show 
</body> 

app.js

var app = angular.module('app', []) 
    .filter('to_trusted', ['$sce', function($sce) { 
    return function(text) { 
     return $sce.trustAsHtml(text); 
    }; 
}]); 

app.controller('MainCtrl', function($scope) { 
    $scope.sup = true; 
    $scope.dynamic = ["Humpty Dumpty sat on a wall.<ref><sup>1</sup></ref>", 
        "Humpty Dumpty had a great fall.<ref><sup>2</sup></ref>"]; 
}); 

app.directive('sup', function($compile) { 
    return { 
    restrict: 'E', 
    link: function(scope, element) { 
     scope.$watch('sup', function() { 
     element.css({ display: scope.sup ? 'inline' : 'none' }); 
     }); 
    } 
}}); 
+0

,我不知道这是任何相关的,但我认为这可能是有用的 http://stackoverflow.com/questions/26447885/how-directives-are-invoked-if -an-element-that-c​​ontained-a-directive-is-added-dyna – 2014-10-20 17:54:05

+0

@KevinB不够公平。 – ScottD 2014-10-20 18:14:01

+0

[angular ng-bind-html-unsafe及其内部指令]可能重复(http://stackoverflow.com/questions/17417607/angular-ng-bind-html-unsafe-and-directive-within-it) – 2014-10-20 18:19:19

回答

0

你必须改变你的指令,像下面。

app.directive('compile', ['$compile', function ($compile) { 
    return function (scope, element, attrs) { 
     scope.$watch(
     function (scope) { 
      return scope.$eval(attrs.compile); 
     }, 
     function (value) { 
      element.html(value); 
      $compile(element.contents())(scope); 
     } 
    ); 
    }; 
}]); 

然后在这样的html中使用它。

<h3>Dynamic Example</h3> 
<div ng-repeat="item in dynamic"> 
    <span compile="item"></span> 
</div> 

Demo code