AngularJS - 按需加載 - require

index.html

<html>
  <head>
    <style>
      .active { 
        color: red; 
        font-weight: bold; 
      }
    </style>
  </head>
  <body>
    <a ui-sref="hello" ui-sref-active="active">Hello</a>
    <a ui-sref="about" ui-sref-active="active">About</a>
    <ui-view></ui-view>
    <script src="app/lib/require.js"></script>
    <script src="main.js"></script>
  </body>
</html>

main.js

require.config({
    baseUrl: 'app',
    paths: {
        'app': 'app',
        'angular': 'lib/angular.min',
        'router': 'lib/angular-ui-router.min'
    },
    shim: {
        'angular': {exports: 'angular'},
        'router': {deps: ['angular']},
        'app': {deps: ['router']}
    }
})
require(['app'], function() {
    angular.bootstrap(document, ['app'])
})

app.js

define([], function() {
    var app = angular.module('app', ['ui.router']);
    app.config(function($controllerProvider, $compileProvider, $filterProvider, $provide) {
        app.register = {
            controller: $controllerProvider.register,
            directive: $compileProvider.directive,
            filter: $filterProvider.register,
            service: $provide.service
        };
    })
    app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('hello');
        $stateProvider
            .state("hello", {
                url: "/hello",
                controller: 'helloCtrl',
                templateUrl: 'app/hello/view/hello.html',
                resolve: {
                    loadCtrl: ["$q", function($q) {
                        var deferred = $q.defer();
                        require([
                            'hello/controller/hello.controller'
                        ], function() { deferred.resolve(); });
                        return deferred.promise;
                    }]
                }
            })
    }])
    return app;
})

hello.controller.js

define(['app'],function(app){
    var helloCtrl = ['$scope', function($scope){  
        $scope.name1 = 'hello world!';
    }];  
	app.register.controller('helloCtrl', helloCtrl)
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章