使用ng的頁面中一般都是使用模塊自動加載,頁面的結構一般是這樣的
- 加載angularjs腳本
- 加載業務代碼腳本(或者寫在script標簽中)
- html結構代碼(帶有ng指令)
就像這樣
app.html
<html> <head> <script src="angular.js"></script> <script src="mypage.js"></script> </head> <body ng-app="app" ng-controller="ctrl"> <h1 ng-bind="Model.Name"></h1> </body> </html>
mypage.js
var app = angular.module("app", []); var ctrl = app.controller("ctrl", function ($scope, $http) { $scope.Model = { Name: "ABC" }; });
大部分情況mypage.js只要在angularjs后面的任意位置都可以。
但是,如果mypage.js是異步加載的,例如script加上了 async,或者使用requirejs等模塊化腳本,那么ng將會出錯
解決方法:
- 在業務代碼后面給dom添加controller指令
- 使用angularjs的模塊手動加載函數bootstrap
要注意的是,module和controller(即下面的app和ctrl)的定義 要在bootstrap執行之前
var app = angular.module("app", []); var ctrl = app.controller("ctrl", function ($scope, $http) { $scope.UI = { Model: { NickName: "ABC", Password: "" } }; });
angular.bootstrap(document, ['app']);
angular.element(document).find('body').attr({ "ng-controller": "Ctrl" });
angular.element(document).find('html').addClass('ng-app');