1

In this plunk I have an Angular UI tab that displays HTML content. Each content has a div containing an ng-click directive, that doesn't work. Most likely the directive needs to be compiled? how to achieve that?

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);
     };

});
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • it would be better if you didn't store template content in variables, and instead used `ng-template`. – Claies Apr 03 '17 at 01:53
  • I just need to define a div in the tab and later I will add dynamically more content, that's why I cannot use a template – ps0604 Apr 03 '17 at 01:54

2 Answers2

0

This is the answer, compile using this directive:

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);
            });
        }
    };
});

see here

Community
  • 1
  • 1
ps0604
  • 1,227
  • 23
  • 133
  • 330
0

Instead change the implementation.

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);
     };

});
   
<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>

Other best way is to use directives.

<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>
Shivaji Varma
  • 690
  • 13
  • 24