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

  • 相关阅读:
    【HDU3681】Prison Break-状态压缩DP+BFS+二分答案
    【BashuOJ3520】警察局长-最短路树+树上背包+概率DP
    【POJ1201】Intervals-差分约束系统+单源最长路
    【BashuOJ2041】最大矩形-矩阵型DP
    【BashuOJ2041】最大矩形-矩阵型DP
    deleted
    deleted
    deleted
    deleted
    deleted
  • 原文地址:https://www.cnblogs.com/TiestoRay/p/5007355.html
Copyright © 2020-2023  润新知