绑定和解析HTML内容

Aym*_*man 2 angularjs

我正在使用AngularJS v1.2.1。

改进的ng-bind-html指令使我可以将不安全的HTML信任到我的视图中。

HTML:

<div ng-repeat="example in examples" ng-bind-html="example.content()"></div>
Run Code Online (Sandbox Code Playgroud)

JS:

function controller($scope, $sce)
{

    function ex()
    {
        this.click = function ()
        {
            alert("clicked");
        }

        this.content() = function ()
        {
            //if
            return $sce.trustAsHtml('<button ng-click="click()">some text</button>'); 
            // no problem, but click is not called

            //when
            return $sce.parseAsHtml('<button ng-click="click()">some text</button>'); 
            //throw an error
        }
    }

    $scope.examples = [new ex(), new ex()];

}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何绑定可能包含Angular表达式或指令的HTML内容?

Sar*_*rah 5

如您的问题所示,如果每个元素都需要动态模板,则一种解决方案是在指令中使用$ compile在本地范围的上下文中解析HTML。在此Plunk中显示了一个简单的版本。

指令示例:

app.directive('customContent', function($compile) {
  return function(scope, el, attrs) {
    el.replaceWith($compile(scope.example.content)(scope));
  }
});
Run Code Online (Sandbox Code Playgroud)

相应的HTML:

<div ng-repeat="example in examples">
  <div custom-content></div>
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,在Plunk控制器中,为简单起见,我将click函数拉到了范围内,因为在模板HTML中,您是在范围的上下文中而不是在示例对象上调用click()。如果您要这样做,可以通过多种方式为每个示例使用不同的点击功能。这个egghead.io截屏视频很好地说明了将表达式显式传递给指令的示例。在您的情况下,取决于您的需要,它可以是单击函数或整个示例对象。