AngularJS Dynamic HTML binding method analysis

Source: Internet
Author: User
This article mainly introduces AngularJS's method of dynamically binding HTML, and analyzes AngularJS's usage and usage of related operation commands for dynamically binding HTML with examples, for more information about how to dynamically bind HTML to AngularJS, see the example in this article. We will share this with you for your reference. The details are as follows:

In front-end Web development, we often encounter the need to dynamically bind some HTML strings from the backend or dynamically spliced to the page DOM display, especially in the Content Management System (CMS: is short for Content Management System.

For angular readers, they will first think of ngBindHtml. For example, angular provides us with this command to dynamically bind HTML. It will bind the calculated expression results to the DOM using innerHTML. However, the problem is not that simple. In Web security, XSS (Cross-site scripting, script injection attacks) is a typical computer security vulnerability in Web applications. XSS attacks are attacks by injecting executable client code to webpages and successfully being executed by browsers, forming an effective XSS attack. Once the attack succeeds, it may obtain sensitive information of users, change user experience, induce users and other illegal behaviors, sometimes XSS attacks are combined with other attack methods, such as SQL injection attacks, server and database attacks, Click hijacking, and relative link hijacking. The attack brings great harm, it is also the top competitor of web security. For more Web security questions, refer to the wiki https://en.wikipedia.org/wiki/Cross-site_scripting%E3%80%82

By default, angular does not trust the added HTML content. For the added HTML content, you must first use $ sce. trustAsHtml to tell angular that this is a trusted HTML content. Otherwise, you will get an exception error of $ sce: unsafe.

Error: [$ sce: unsafe] Attempting to use an unsafe value in a safe context.

The following is a demo of binding simple angular links:

HTML:

JavaScript:

angular.module("com.ngbook.demo", [])  .controller("DemoCtrl", ["$sce", function($sce) {    var vm = this;    var html = '

hello angular

'; vm.html = $sce.trustAsHtml(html); return vm; }]);

For simple static HTML, this problem is solved. For complex HTML, the complexity here refers to HTML templates with angular expressions and instructions. For them, we not only want to bind large DOM display, angular's powerful bidirectional binding mechanism is also expected. NgBindHhtml is not associated with $ scope for two-way binding. If ngClick, ngHref, ngSHow, ngHide, and other angular commands exist in HTML, they are not compile. Click these buttons, and the bound expression is not updated. For example, if you try to change the last link to ng-href = "demo. link", the link will not be parsed and the HTML string will still be seen in the DOM.

All commands in angular must pass through compile and include pre-link and post-link in the compile to take effect. Only specific actions can be connected. In most cases, compile is automatically executed when angular is started. However, for dynamically added templates, You need to manually compile them. Angular provides us with the $ compile service to implement this function. The following is a General compile example:

HTML:

  
   
   change

JavaScript:

angular.module("com.ngbook.demo", [])  .directive("dyCompile", ["$compile", function($compile) {    return {      replace: true,      restrict: 'EA',      link: function(scope, elm, iAttrs) {        var DUMMY_SCOPE = {            $destroy: angular.noop          },          root = elm,          childScope,          destroyChildScope = function() {            (childScope || DUMMY_SCOPE).$destroy();          };        iAttrs.$observe("html", function(html) {          if (html) {            destroyChildScope();            childScope = scope.$new(false);            var content = $compile(html)(childScope);            root.replaceWith(content);            root = content;          }          scope.$on("$destroy", destroyChildScope);        });      }    };  }])  .controller("DemoCtrl", [function() {    var vm = this;    vm.html = 'hello : angular';    vm.link = 'https://angular.io/';    var i = 0;    vm.change = function() {      vm.html = 'change after : ' + (++i) + '';    };  }]);

A dy-compile command is created here. It first listens to changes in the html value of the binding attribute. When the html content exists, it tries to create a subscope first, then, the $ compile service is used to dynamically connect the imported html and replace the current DOM node. The reason for creating a sub-scope is that every time DOM is destroyed, it is also easy to destroy the scope, remove the watchers function brought about by HTML compile, and attempt to destroy the scope when the final parent scope is destroyed.

With the compilation and connection of compile above, the ngHref command will take effect. Here is just an example of the dynamic compile angular module. For specific implementation methods, please refer to your business to declare specific direve ve.

I hope this article will help you with AngularJS programming.

For more AngularJS Analysis on Dynamic HTML binding methods, refer to the PHP Chinese website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.