Home  >  Article  >  Web Front-end  >  Implement dynamic compilation of methods added to dom through AngularJS

Implement dynamic compilation of methods added to dom through AngularJS

高洛峰
高洛峰Original
2017-03-25 16:12:111774browse

The example in this article describes how AngularJS implements dynamic compilation and adds it to the dom. Share it with everyone for your reference, the details are as follows:

When using angularjs, I hope to dynamically build the angular template and then display it through angular.

The usage method is as follows:

<html ng-app="app">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script src="assets/angular.min.js"></script>
  <script src="assets/js/jquery.min.js"></script>
  <script src="assets/js/handlebars.min.js"></script>
  <script src="assets/Handlebars.helper.js"></script>
  <script >
  var app=angular.module("app",[]);
  app.controller(&#39;ctrl&#39;, [&#39;$scope&#39;,&#39;$compile&#39;,function($scope,$compile){
    $scope.userName=&#39;RAY&#39;;
    $scope.test = function test(){
      console.log(&#39;你好:&#39; +$scope.userName);
    }
    //通过$compile动态编译html
    var html="<button ng-click=&#39;test()&#39;>{{userName}}</button>";
    var template = angular.element(html);
    var mobileDialogElement = $compile(template)($scope);
    angular.element(document.body).append(mobileDialogElement);
  }]);
  </script>
</head>
<body ng-controller="ctrl">
</body>
</html>
var html="<button ng-click=&#39;test()&#39;>{{userName}}</button>";

This kind of code is the angular template. By compiling it through the angularjs compiler, you can access the object data in the angular scope.

The above is the content of AngularJS’s method of dynamically compiling and adding to dom. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Related articles:

AngularJS dynamically generates div IDs

AngularJs dynamically loads modules and dependencies

AngularJS implements methods of binding events to dynamically generated elements

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn