Angular.js $ compile returns an html array but not the actual html

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 expect it to generate input, some range, connected through the scope and break. However, I get this output:

[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]]

I also tried the template, in a comment here, separately, and then commenting out part of the link. This generates input and fault elements, but not a range that shows the associated SampleData input model.

I have a non-working sample at http://jsfiddle.net/KvdM/nwbsT/ that demonstrates it.

+6
source share
5 answers

Try the following:

 element.html(markup); $compile(element.contents())(scope); 
+15
source

Running the function returned by the $ compilation service gives you DOM elements, not html. Therefore, you need to paste them into your page using append (or equivalent):

 angular.element(element).append($compile(markup)(scope)); 
+9
source

Perhaps the easiest way is to use a hard-coded template rather than a dynamically 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/>", }; }); 

Fiddle

+1
source

Depending on what data should be compiled, Angular returns a node comment several times.

The corresponding node we want to use is 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(); }); 
-1
source

You just need to add jquery to use ".html" and fix the ng-model names

-1
source

Source: https://habr.com/ru/post/950357/


All Articles