In application-level development, we often try to show a piece of HTML dynamically, which is a very common feature, but angular does not give a solution directly, so what should we do?
When it comes to how to implement dynamic attempts, we have to study the Angular-router,angular-router provides a dynamic routing, dynamic attempt of the mechanism.
Angular-router version: AngularJS v1.3.9-local+sha.a3c3bf3
Line No. 975:
1Ngviewfillcontentfactory. $inject = [' $compile ', ' $controller ', ' $route '];2 functionngviewfillcontentfactory ($compile, $controller, $route) {3 return {4Restrict: ' ECA ',5Priority:-400,6Linkfunction(scope, $element) {7 varCurrent =$route. Current,8Locals =current.locals;9 Ten $element. HTML (locals. $template); One A varlink =$compile ($element. Contents ()); - - if(current.controller) { theLocals. $scope =scope; - varController =$controller (Current.controller, locals); - if(Current.controlleras) { -Scope[current.controlleras] =Controller; + } -$element. Data (' $ngControllerController ', controller); +$element. Children (). Data (' $ngControllerController ', controller); A } at - link (scope); - } - }; -}
This is the instruction code of Ngview, here we mainly focus on two words:
$element. HTML (locals. $template);//inserts the read HTML into the corresponding DOM object
var link = $compile ($element. Contents ());//Compile HTML template
So, the new template (trying) just needs to be newly compiled.
All right, so let's do an auxiliary method (I just learned angular a lot of things have not come to the urgent study, to jquery familiarity, so the following auxiliary method uses jquery):
(function () { varCompileview =function(DOM) {//get the app where the DOM is located varAppelement = $ (DOM). Closest (". Ng-scope[ng-app]"); //get the app's injector varInjector = Appelement.data ("$injector"); Injector.invoke (function($compile) {varScope =$ (DOM). scope (); //compile template (try)$compile ($ (DOM)) (scope); //Notification Changesscope. $apply (); }); } //Extended Angular$.extend (angular, {//Dynamic compilation attempts toCompileview:compileview}); //based on the extension of jquery, it realizes the dynamic attempt$.fn.compileview =function () { varDom = This; Compileview ( This); }}) (JQuery);
Here are two ways to do this: a jquery-based extension and a angular-based extension.
The code is simple, not much to explain, to an example:
1 $ (function () {2 $ ("#btnLoadView"). Click (function () {3 function () {4 angular.compileview (this); 5 }); 6 7});
Angular's dynamic attempt to learn notes