Reputation: 16613
I have the following code:
app.directive('mySample', function($compile) {
return {
//template:"<input type='text' ng=model='sampleData'/> {{sampleData}} <br/>"
link: function(scope, element, atts, controller) {
var markup = "<input type='text' ng=model='sampleData'/> {{sampleData}} <br/>";
angular.element(element).html($compile(markup)(scope));
console.log($compile(markup)(scope));
}
};
});
And I would expect it to generate an input, some span that's coupled via the scope and a break. However I get this output:
[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]]
I also tried the template, in comment here, separately and then commenting out the link part. That generates the input and break elements but not the span that shows the coupled model input sampleData.
I have a non-working sample at http://jsfiddle.net/KvdM/nwbsT/ that demonstrates it.
Upvotes: 7
Views: 11441
Reputation: 1477
You just needed to add the jquery to use ".html" and fixed the naming of ng-model
Upvotes: -1
Reputation: 9
Depends on what kind of data should to be compiled, some times Angular returns a comment node type.
The relevant node that we want to use is the next()
(its first sibling).
var tpl = '<div class="myWidget" ng-include="'templates/myWidget.html'"></div>;
var _myWidget = $compile(tpl)(scope);
var myWidget = null;
scope.$on('$includeContentLoaded', function () {
myWidget = _myWidget.next();
});
Upvotes: -1
Reputation: 43947
Try this:
element.html(markup);
$compile(element.contents())(scope);
Upvotes: 15
Reputation: 54543
Maybe the easiest way is to use a hard-coded template rather than a dynamic generated one
<div ng-app="myApp">
<my-sample sample-data="'test'"></my-sample>
</div>
var app = angular.module('myApp', []);
app.directive('mySample', function ($compile) {
return {
restrict: 'E',
scope: {
sampleData: '=sampleData'
},
template: "<input type='text'/> {{sampleData}} <br/>",
};
});
Upvotes: 1
Reputation: 11391
Running the function returned by the $compile service gives you DOM elements rather than html. So you need to insert them into your page using append (or equivalent):
angular.element(element).append($compile(markup)(scope));
Upvotes: 10