requirejs AngularJS结合使用示例解析

 更新时间:2023年06月30日 11:18:52   作者:Skywang  
这篇文章主要为大家介绍了requirejs AngularJS结合使用示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

引言

最近一个项目要使用requirejs实现angularjs的js文件按需加载,在网上我也找了很多资料但是都不是很全,要么就不是很详细,所以我自己总结了一下,有需要的朋友可以看一下。废话不多说,直接上代码。

一、简单事例的项目目录如下:

index.html

js文件夹

--controller文件夹
  --- controllers.js
  --- controller1.js
  ---controller2.js
--directives文件夹
  ---directives.js
  ---directive1.js
--app.js
--router.js
--loader.js
--main.js
--angular-bootstrap.js

二、首页

首先你的index.html大概如下

   <!doctype html>
    <!-- <html xmlns:ng="//angularjs.org" id="ng-app" 
   ng-app="webApp"> -->
   <htmls>
   <head> 
   <meta charset="utf-8"> 
   <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
  </head>
      <body>
    <!--其他html内容-->
       <script data-main="js/main" src="../lib/require/require.min.js"></script>
      </script>
    </body>
</html>

在首页index.html只需要引入requireJs库文件,并且指明入口函数main.js,采用手动启动angularjs应用,所以这里不用为首页添加ng-app='webApp'。

三、配置mian.js

定义RequireJS配置

require.config({
urlArgs: "==version==",
waitSeconds: 0,
paths: {
'jquery': '../../plugins/jQuery/jQuery-2.1.4.min',
'bootstrap': '../../lib/bootstrap/dist/js/bootstrap.min',
'angular': '../../lib/angular/angular.min',
'angular-route': '../../lib/angular-route/angular-route.min',
'angular-animate': '../../lib/angular-animate/angular-animate.min',
'angular-resource': '../../lib/angular-resource/angular-resource.min',
'angular-growl': '../../lib/angular-growl-v2/build/angular-growl.min',
'domReady': '../../lib/require/domReady',
'jquery-ui': '../../lib/jquery-ui/jquery-ui.min',
},
shim: {
'angular': {
exports: 'angular',
deps: ['jquery']
},
'bootstrap': {
deps: ['jquery']
},
'angular-route': {
deps: ['angular']
},
'angular-animate': {
deps: ['angular']
},
'angular-resource': {
deps: ['angular']
},
'angular-growl': {
deps: ['angular']
},
'slimscroll': {
deps: ['jquery']
},
'tools': {
deps: ['jquery']
},
'configs': {
deps: ['jquery']
},
},
deps: [
'index-app',
'tools',
'configs',
]
});
require([
 'app',
 'routes',
         // 这是导入一个方法
 'loader',
 //注意:这不是Twitter Bootstrap,而是AngularJS bootstrap
 'angular-bootstrap',
 //所创建的所有控制器、服务、指令及过滤器文件都必须写到这里,这块内容必须手动维护
 'controllers/controllers',
 'directives/directives',
       ],
   function(app, config, loader) {
 'use strict';
 app.config([
     '$routeProvider',
     '$locationProvider',
     '$controllerProvider',
     '$compileProvider',
     '$filterProvider',
     '$provide',
     "$httpProvider",
     'growlProvider',
     function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $httpProvider, growlProvider) {
         app.registerController = $controllerProvider.register;
         app.registerDirective = $compileProvider.directive;
         app.registerFilter = $filterProvider.register;
         app.registerFactory = $provide.factory;
         app.registerService = $provide.service;
         console.log("config.routes"+config.routes);
         if(config.routes != undefined) {
             angular.forEach(config.routes, function(route, path) {
                 $routeProvider.when(path, {
                     templateUrl: route.templateUrl,
                     controller: route.controller,
                     resolve: loader(route.dependencies)
                 });
             });
         }
         if(config.defaultRoutePath != undefined) {
             $routeProvider.otherwise({
                 redirectTo: config.defaultRoutePath
             });
         }
         growlProvider.globalTimeToLive({
             success: 3000,
             error: 5000,
             warning: 5000,
             info: 5000
         });
         $httpProvider.defaults.withCredentials = true;
         $httpProvider.defaults.useXDomain = true;
         delete $httpProvider.defaults.headers.common['X-Requested-With'];
     }
 ]);
 return app;
 }
 );

所以总体上说main.js这个文件做的事情就是:由requirejs异步载入所有文件;

function里面就是各种依赖方法。

四、手动启动angularjs应用

angular-bootstrap.js文件

    //当DOM结构加载完成后,bootstrap.js文件将会命令AngularJS启 动起来并继续执行
    define(['angular', 'domReady', 'app'], function(angular, domReady) {
    require(['domReady!'], function(document) {
        angular.bootstrap(document, ['app']);
       });
    });

这里依赖于app.js和router.js,我们看看这两个文件分别做什么

五、angular.module

这时先看看平时我们在写angularjs应用是这样写的

  var app = angular.module("xxx",["xxx"]);
  app.controller("foo",function($scope){});
  app.directive(...)

所以app.js里是这样的

 define([
'angular',
'angular-route',
'angular-resource',
'angular-animate',
'angular-growl',
'angular-animate',
     。。。
 ], function(angular) {
'use strict';
return angular.module('app', [
    'controllers',
    'directives',
    'angular-growl',
    'ngAnimate',
    'ngRoute',
     。。。
   ]);
});

六、网站路由设置

我们这里使用ng-router。所以我们的router.js应该是这样的,主要是用来定义路由的,关于ng-router的配置请自行查看相关知识,这里就简单略过

router.js

   define([], function() {
return {
    defaultRoutePath: '/index',
    routes: {
        '/index': {
            templateUrl: 'tpls/index.html',
            controller: 'indexCtr',
            dependencies: ['js/controllers/index.js', 'js/directives/derective1.js']
            //这就是按需导入js文件
        },
    }
};
});

当然还需要有loader文件 里面有我们定义按需加载的方法;

loader.js

define([], function() {
  return function(dependencies) {
// 返回路由的 resolve 定义, 
var definition = {
  // resolver 是一个函数, 返回一个 promise 对象;
  resolver: ['$q', '$rootScope', function($q, $rootScope) {
    // 创建一个延迟执行的 promise 对象
    var defered = $q.defer();
    // 使用 requirejs 的 require 方法加载的脚本
    require(dependencies, function() {
      $rootScope.$apply(function() {
        // 加载完脚本之后, 完成 promise 对象;
        defered.resolve();
      });
    });
    //返回延迟执行的 promise 对象, route 会等待 promise 对象完成
    return defered.promise;
  }]
};
return definition;
  }
 });

七、控制器

首先 controllers.js里我们要这样写

 define(['angular'], function(angular) {
      'use strict';
          var controllers = angular.module('controllers', []);
   controllers.config([ '$controllerProvider', function($controllerProvider) {
        controllers.registerController = $controllerProvider.register;
}
  ]);
  controllers.initController = function(controllerName, options) {
        var attrs = [];
        var fun = null;
      if(jQuery.isArray(options)) {
                attrs = options.slice(0, options.length - 1)
                fun = options[options.length - 1]
         } else {
            fun = options;
        }
        controllers.registerController(controllerName, fun);
          if (attrs.length &gt; 0)
            fun.$inject = attrs;
          }
    return controllers;
  });

主要用来加载各个控制器(所有的控制器都将在这个文件中被加载),除此之外再不用做其他,因为我们可以有很多个控制器文件,按照具体需要进行添加。

contreller1.js里要这样写 这就是我们具体的控制器

  define(['controllers/controllers'], function(controllers) {
      'use strict';
  controllers.initController('user_centerCtrl', ['$scope', '$location', '$routeParams', '$timeout', '$http',
    function($scope, $location, $routeParams, $timeout, $http) {
        }
    ]);
 });

八、指令

同理directives.js也类似。

define(['angular'], function(angular) {
'use strict';
var directives = angular.module('directives', []);
directives.config([
'$compileProvider',
function($compileProvider) {
  directives.registerDirective = $compileProvider.directive;
      }
]);
directives.initDirective = function(directiveName, options) {
var attrs = [];
var fun = null;
if(jQuery.isArray(options)) {
  attrs = options.slice(0, options.length - 1)
  fun = options[options.length - 1]
} else {
  fun = options;
}
directives.registerDirective(directiveName, fun);
if (attrs.length > 0)
  fun.$inject = attrs;
}
return directives;
});

directive1.js

define(['directives/directives'],
  function(directives) {
  'use strict';
directives.initDirective("oprationtable", function() {
    return {
        restrict: 'AE',
        templateUrl: "tpls/operationTable.html",
        transclude: true,
        scope: {
            tabdata: '=',
        },
        link: function(scope, elem, attrs) {
            //console.log(attrs.tabdata)
            //scope.tabdata = attrs.tabdata
            //console.log(scope.tabdata)
        },
        controller: function($scope, $element, $attrs) {
        },
     }
 });
});

好了 剩下的服务啊过滤器啊都可以这样写,这就是比较完整requirejs和AngularJS结合使用项目搭建 希望对大家有帮助!

更多关于requirejs AngularJS使用的资料请关注脚本之家其它相关文章!

相关文章

最新评论