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');

 

转载于:https://www.cnblogs.com/TiestoRay/p/5007355.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值