search

Home  >  Q&A  >  body text

angular.js - How to manually compile inserted dom in angular?

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~

滿天的星座滿天的星座2777 days ago735

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-05-15 16:53:11

    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);
          });
        }
      };
    });
    

    html

    html<p jxb-bind-compiled-html="htmlvariable">
    </p>
    

    htmlvariable is the html code variable that needs to be inserted

    reply
    0
  • 迷茫

    迷茫2017-05-15 16:53:11

    http://stackoverflow.com/questions/11771513/angularjs-jquery-how-to-get-dynamic-content-working-in-angularjs

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-15 16:53:11

    <!DOCTYPE HTML>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
        <title>angular编译插入到dom的元素</title>
    </head>
    <body ng-controller="appCtrl">
        
        <!-- javascript
            ================================================== -->
        <script src="http://cdn.staticfile.org/jquery/2.1.0/jquery.min.js" type="text/javascript"></script>
        <script src="http://cdn.staticfile.org/angular.js/1.2.0rc3/angular.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            var app = angular.module('app', []);
            app.controller('appCtrl', function ($scope, $compile) {
                $scope.arrs = [1,2,3,4,5,"成", "功", "编", "译"];
                var html = '<h1 ng-repeat="arr in arrs">{{ arr }}</h1>';
                
                // 编译html
                $html = $compile(html)($scope);
                // 插入到dom
                $('body').before($html);
            });
            angular.bootstrap(document, ['app']);
        </script>
    </body>
    </html>

    I wrote an example, as above.

    reply
    0
  • Cancelreply