Here, I am trying to replace the table row through directive and compile function. Somehow, the scope is not linking to newly added template. Here is the really simple code. Created a plnkr here: http://plnkr.co/edit/toAxkoLkWSIxYJU06iuW?p=preview
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<!-- <script src="app.js"></script>-->
</head>
<body>
<h1> stand alone </h1>
<!-- <row></row>
-->
<h1>in table</h1>
<table>
<tr><td> Row 1</td></tr>
<tr sda-data-embed='true' row><td>my row goes here</td></tr>
<tr><td> Row 4</td></tr>
</table>
<script>
var app = angular.module('plunker', []);
app.directive('row', function($compile) {
var template = '<tr><td>Row 2: This is good</td></tr><tr><td>Row 3: {{name.firstName}}</td></tr>';
return {
restrict: 'EA',
replace: true,
scope:{},
/*template: function(element, attrs) {
var templ = template;
if (!attrs.sdaDataEmbed) {
templ = '<table>' + template + '</table>';
}
return templ;
},*/
compile: function(element, attrs) {
//$scope.firstName = 'Y';
var templ = template;
if (!attrs.sdaDataEmbed) {
templ = '<table>' + template + '</table>';
}
element[0].outerHTML = templ;
},
controller: ['$scope', DataController]
}
function DataController($scope) {
$scope.name = {};
$scope.name.firstName = 'Gosh';
}
});
</script>
</body>
</html>
UPDATE : Later I found how to replace the table row, not sure if it is recommended but it works! I replaced, compiled the html element from link function. here is the code.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<!-- <script src="app.js"></script>-->
</head>
<body>
<h1> stand alone </h1>
<div>
<my-row></my-row>
</div>
<h1>in table</h1>
<table>
<tr>
<td>Row 1</td>
</tr>
<tr sda-data-embed='true' my-row>
<td>my row goes here</td>
</tr>
<tr>
<td>Row 4</td>
</tr>
</table>
<script>
var app = angular.module('plunker', []);
app.directive('myRow', function($compile) {
var template = '<tr><td>Row 2: This is good</td></tr><tr><td>Row 3: {{name.firstName}}</td></tr>';
return {
restrict: 'EA',
replace: true,
scope: {},
link: function(scope, element, attrs) {
var templ = template;
if (!attrs.sdaDataEmbed) {
templ = '<table>' + template + '</table>';
}
var e = $compile(templ)(scope);
element.replaceWith(e);
},
controller: ['$scope', DataController]
}
function DataController($scope) {
$scope.name = {};
$scope.name.firstName = 'Gosh';
}
});
</script>
</body>
</html>