angular.js - How to manually compile inserted dom in angular?
滿天的星座2017-05-15 16:51:11
0
3
725
After performing some operations on the page, a piece of html code will be inserted
How to compile this html so that the events and variables bound to it take effect~
For security reasons, the events in the html code we inserted and the bound ng-model will not work.
If you want it to work, you need to use angular’s $compile service
I usually use a directive when processing
javascriptangular.module(...).directive('jxbBindCompiledHtml', function ($compile) {
'use strict';
return {
template: '
<p></p>
',
scope: {
rawHtml: '=jxbBindCompiledHtml'
},
link: function (scope, elem, attrs) {
scope.$watch('rawHtml', function (value) {
if (!value) {
return;
}
// we want to use the scope OUTSIDE of this directive
// (which itself is an isolate scope).
var newElem = $compile($.parseHTML(value))(scope.$parent);
elem.contents().remove();
elem.append(newElem);
});
}
};
});
For security reasons, the events in the html code we inserted and the bound ng-model will not work.
If you want it to work, you need to use angular’s $compile service
I usually use a directive when processing
html
htmlvariable is the html code variable that needs to be inserted
http://stackoverflow.com/questions/11771513/angularjs-jquery-how-to-get-dynamic-content-working-in-angularjs
I wrote an example, as above.