AngularJS之手动加载模块app和controller

 

使用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将会出错

 解决方法:

  1. 在业务代码后面给dom添加controller指令
  2. 使用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');

 

posted @ 2015-11-30 15:39  TiestoRay  阅读(2414)  评论(3编辑  收藏  举报