如何在Angular UI选项卡中编译动态内容?

时间:2017-04-03 01:44:07

标签: angularjs angular-ui-bootstrap angular-ui

In this plunk我有一个显示HTML内容的Angular UI标签。每个内容都有div,其中包含ng-click指令,但该指令不起作用。很可能该指令需要编译?怎么实现呢?

HTML

  <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-bind-html="tab.content"></div>
    </uib-tab>
  </uib-tabset>

的Javascript

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content:'<div ng-click="click(1)" id="id1">111</div>' },
       { title:'title 2', content:'<div ng-click="click(2)" id="id2">222</div>' }
     ];


     $scope.click = function(i){
       alert(i);
     };

});

2 个答案:

答案 0 :(得分:0)

这是答案,使用此指令编译:

app.directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };
});

请参阅here

答案 1 :(得分:0)

而是改变实施。

&#13;
&#13;
var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content: {id:1, label: 111} },
       { title:'title 2', content: {id:2, label: 222} }
     ];


     $scope.click = function(i){
       alert(i);
     };

});
&#13;
   
<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-click="click(tab.content.id)" id="id{{tab.content.id}}">{{tab.content.label}}</div>
    </uib-tab>
  </uib-tabset>
&#13;
&#13;
&#13;

其他最好的方法是使用指令。

<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <my-directive my-click="click(tab.content.id)" my-content="tab.content"</directive-x>
    </uib-tab>
  </uib-tabset>