Nodejs+AngularJS模块之Angular依赖注入
Angular模块
Angular模块是一种容器,它让你把代码隔离并组成简洁、整洁、可重复使用的块。模块本身不提供直接的功能,但它们包含其他提供功能的对象的实例,如控制器、过滤器、服务、动画等。
需要的模块
//express模块
npm install express -g
idea项目结构
1.基本的nodejs静态Web服务器
代码
var express = require('express');
var app = express();
app.use('/', express.static('./static')).
use('/images', express.static( '../images')).
use('/lib', express.static( '../lib'));
app.listen(80);
2.在控制器和模块定义中实现依赖注入
代码
injector.js
var myMod = angular.module('myMod', []);
myMod.value('modMsg', 'Hello from My Module');
myMod.controller('controllerB', ['$scope', 'modMsg',
function($scope, msg) {
$scope.message = msg;
}]);
var myApp = angular.module('myApp', ['myMod']);
myApp.value('appMsg', 'Hello from My App');
myApp.controller('controllerA', ['$scope', 'appMsg',
function($scope, msg) {
$scope.message = msg;
}]);
console.log(myApp.requires);
//var controller = function($scope, msg) {
// $scope.message = msg;
//};
//controller['$inject'] = ['$scope', 'appMsg'];
//myApp.controller('controllerA', controller);
injector.html
<!doctype html>
<html ng-app="myApp">
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<div ng-controller="controllerA">
<h2>Application Message:</h2>
{{message}}
</div><hr>
<div ng-controller="controllerB">
<h2>Module Message:</h2>
{{message}}
</div>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script src="/js/injector.js"></script>
</body>
</html>
结果
在http://code.angularjs.org/1.2.9/angular.min.js 最好下载,防止网络出现问题
游览器输入http://localhost/injector.html 出现如下图: