Working with DOM maneuvers in AngularJS

When I do a DOM manipulation (add new HTML) using jQuery, AngularJS does not automatically detect the variables in the new HTML and replace them with its values. For example:

$scope.showSummary = function($event){ $($event.currentTarget).html("<div>{{row}}</div>"); }; 

This is a simple example, but after changing the HTML in the element (this function was called by ng-click ), the output is still {{row}} instead of what the string should mean in context / area.

+36
angularjs
Jul 28 2018-12-12T00:
source share
2 answers

You need to enter $compile ( http://docs.angularjs.org/api/ng.$compile ) and use it so that angular knows about the new html.

$compile('<div>{{row}}</div')($scope).appendTo($event.currentTarget);

However, angular does not allow DOM manipulation in your controllers. You want your controllers to process the business and your views to process the view.

Try to indicate what you want to do. http://docs.angularjs.org/guide/directive

+66
Jul 28 2018-12-12T00:
source share

If you use snippets for new elements (for example, $ ("<" + "div>"). AppendTo ("body")), using a wrapper similar to the following for jQuery preend / append methods avoids adding elements to the code:

 // run angular-compile command on new content // (also works for prependTo/appendTo, since they use these methods internally) var oldPrepend = $.fn.prepend; $.fn.prepend = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldPrepend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; var oldAppend = $.fn.append; $.fn.append = function() { var isFragment = arguments[0][0] && arguments[0][0].parentNode && arguments[0][0].parentNode.nodeName == "#document-fragment"; var result = oldAppend.apply(this, arguments); if (isFragment) AngularCompile(arguments[0]); return result; }; function AngularCompile(root) { var injector = angular.element($('[ng-app]')[0]).injector(); var $compile = injector.get('$compile'); var $rootScope = injector.get('$rootScope'); var result = $compile(root)($rootScope); $rootScope.$digest(); return result; } 
+2
Oct 18 '14 at 17:22
source share



All Articles