AngularJS API之bootstrap啓動

對於通常的使用者來講,AngularJS的ng-app都是手動綁定到某個dom元素。可是在一些應用中,這樣就顯得很不方便了。javascript

綁定初始化

經過綁定來進行angular的初始化,會把js代碼侵入到html中,可是對於新手使用來講,仍是足夠了!html

<html>
<head>
    <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>
</head>
<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>
</html>

運行後,會顯示hello,angular!java

手動初始化

Angular中也提供了手動綁定的api——bootstrap,它的使用方式以下:bootstrap

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

其中第一個參數element:是綁定ng-app的dom元素;
modules:綁定的模塊名字
config:附加的配置api

簡單的看一下代碼:app

<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>

值得注意的是:

  • angular.bootstrap只會綁定第一次加載的對象。
  • 後面重複的綁定或者其餘對象的綁定,都會在控制檯輸出錯誤提示。
相關文章
相關標籤/搜索