requirejs AngularJS結(jié)合使用示例解析
引言
最近一個項目要使用requirejs實現(xiàn)angularjs的js文件按需加載,在網(wǎng)上我也找了很多資料但是都不是很全,要么就不是很詳細,所以我自己總結(jié)了一下,有需要的朋友可以看一下。廢話不多說,直接上代碼。
一、簡單事例的項目目錄如下:
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="http://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內(nèi)容-->
<script data-main="js/main" src="../lib/require/require.min.js"></script>
</script>
</body>
</html>在首頁index.html只需要引入requireJs庫文件,并且指明入口函數(shù)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',
//所創(chuàng)建的所有控制器、服務、指令及過濾器文件都必須寫到這里,這塊內(nèi)容必須手動維護
'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結(jié)構(gòu)加載完成后,bootstrap.js文件將會命令AngularJS啟 動起來并繼續(xù)執(zhí)行
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',
。。。
]);
});
六、網(wǎng)站路由設置
我們這里使用ng-router。所以我們的router.js應該是這樣的,主要是用來定義路由的,關(guān)于ng-router的配置請自行查看相關(guān)知識,這里就簡單略過
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文件
},
}
};
});
當然還需要有l(wèi)oader文件 里面有我們定義按需加載的方法;
loader.js
define([], function() {
return function(dependencies) {
// 返回路由的 resolve 定義,
var definition = {
// resolver 是一個函數(shù), 返回一個 promise 對象;
resolver: ['$q', '$rootScope', function($q, $rootScope) {
// 創(chuàng)建一個延遲執(zhí)行的 promise 對象
var defered = $q.defer();
// 使用 requirejs 的 require 方法加載的腳本
require(dependencies, function() {
$rootScope.$apply(function() {
// 加載完腳本之后, 完成 promise 對象;
defered.resolve();
});
});
//返回延遲執(zhí)行的 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 > 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結(jié)合使用項目搭建 希望對大家有幫助!
更多關(guān)于requirejs AngularJS使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
AngularJS 中的Promise --- $q服務詳解
這篇文章主要介紹了AngularJS 中的Promise --- $q服務詳解方法的相關(guān)資料,需要的朋友可以參考下2016-09-09
詳解Angular路由 ng-route和ui-router的區(qū)別
這篇文章主要介紹了詳解Angular路由 ng-route和ui-router的區(qū)別,分別介紹了兩種路由的用法和區(qū)別,有興趣的可以了解一下2017-05-05
使用AngularJS來實現(xiàn)HTML頁面嵌套的方法
這篇文章主要介紹了使用AngularJS來實現(xiàn)HTML頁面嵌套的方法,主要用到了AngularJS中的ng-include指令,需要的朋友可以參考下2015-06-06
Angular2中constructor和ngOninit的使用講解
這篇文章主要介紹了Angular2中constructor和ngOninit的使用講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

