Initialization of Angular. js Basic Learning

  • 2021-08-03 08:44:14
  • OfStack

1. Binding initialization, auto-load

Initializing an angular by binding intrudes the js code into the html.

ng-app Is an instruction of angular, representing an angular application (also called a module). Use ng-app Or ng-app="" To mark 1 DOM node, so that the framework will load automatically. That is to say, ng-app You can take attribute values.


<body ng-app="myApp">
 <div ng-controller="myCtrl">
  {{ hello }}
 </div>
 <script type="text/javascript">
  var myModule = angular.module("myApp",[]);
  myModule.controller("myCtrl",function($scope){
   $scope.hello = "hello,angular!";
  });
 </script>
</body>

2. Initialize manually

If you want to have more control over initialization, you can use custom manual boot initialization instead of automatic initialization of angular. For example, you need to do something before angular compiles the template, such as changing some contents of the template.

Manually bound api-bootstrap is also available in Angular and is used as follows:


angular.bootstrap(element, [modules], [config]);

Where the first parameter element: Is a binding ng-app dom element of;

modules: Binding module name config: Additional configuration

It is worth noting that:

angular.bootstrap Only the object loaded for the first time is bound. Repeated bindings or bindings of other objects will output an error prompt in the console.

<html>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
<body id="body">
 <div ng-controller="myCtrl">
  {{ hello }}
 </div>
 <script type="text/javascript">
  var app = angular.module("bootstrapTest",[]);
  app.controller("myCtrl",function($scope){
   $scope.hello = "hello,angular from bootstrap";
  });
  
  // angular.bootstrap(document.getElementById("body"),['bootstrapTest']);
  angular.bootstrap(document,['bootstrapTest']);
 </script>
</body>
</html>

<html>
 
 <head>
 <script src="angular.js"></script>
 <script>
 
 //  Create moudle1
 var rootMoudle = angular.module('moudle1', []);
 rootMoudle.controller("controller1",function($scope){$scope.name="aty"});
 
 //  Create moudle2
 var m2 = angular.module('moudle2', []);
 m2.controller("controller2",function($scope){$scope.name="aty"});
 
 
 //  After the page is loaded, , Reload module 
 angular.element(document).ready(function() {
  angular.bootstrap(document.getElementById("div1"),["moudle1"]);
  angular.bootstrap(document.getElementById("div2"),["moudle2"]);
 });
 
 </script>
 
 <head>
 <body>
 <div id="div1" ng-controller="controller1">div1:{{name}}</div>
 <div id="div2" ng-controller="controller2">div2:{{name}}</div>
 </body>
 
</html>

Summarize


Related articles: