Tag Archives: AngularJS

AngularJS Interview Questions and Answers


Angular Interview questions and answers

What is AngularJS ?

Explain Directives in Angular?

What are controllers and need of ng-controller and ng-model in Angular?

What are expressions in Angular?

How can we initialize Angular application data?

Explain $scope in Angular?

What is “$rootScope” and how is it related with “$scope”?

Do I need Jquery for Angular?

How is the data binding in Angular ?

How do we make HTTP get and post calls in Angular?

How do we pass data using HTTP POST in Angular ?

What is dependency injection and how does it work in Angular?

How does DI benefit in Angular?

What are services in Angular?

Are Service object instances global or local?

What is a Factory in Angular?

What is the difference between Factory and Service?

My other interview question articles

Angular Interview questions and answers

AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.

Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk

What is AngularJS ?

“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

function Customer() 
this.CustomerName = "AngularInterview";
var Cust = new Customer();

Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.

<input type=text id="TxtCustomerName" onchange="UitoObject()"/>

So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

function UitoObject() 
Cust.CustomerName = $("#TxtCustomerName").val();
function ObjecttoUi() 

So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.

<div ng-controller="Customer">
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>

In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Explain Directives in Angular?

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.

<input type=text id="txtCustomerName"  ng-model="CustomerName"/>

Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

What are controllers and need of ng-controller and ng-model in Angular?

“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.

Note: – Do not worry too much about the $scope , we will discuss the same in the next question.
function Customer($scope)
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        $scope.Update = function () {

“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.

<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>

What are expressions in Angular?

Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.

Below are some examples of angular expressions:-

The below expression adds two constant values.


The below expression multiplies quantity and cost to get the total value.

The value total cost is {{ quantity * cost }}

The below expression displays a controller scoped variable.

<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}} 
The value of Customer code is {{CustomerCode}}

How can we initialize Angular application data?

We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.

<body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}

Explain $scope in Angular?

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.

For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.

function Function1($scope)
$scope.ControllerName = "Function1";        
function Function2($scope)
$scope.ControllerName = "Function2";

Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.

<div id=&rdquo;div1&rdquo; ng-controller="Function1">
Instance of {{ControllerName}} created 
<div id=&rdquo;div2&rdquo; ng-controller="Function2">
Instance of {{ControllerName}} created 

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?

“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

<script language="javascript">
function Function1($scope, $rootScope) 
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.Counter = $rootScope.Counter;
        $scope.ControllerName = "Function1";
function Function2($scope, $rootScope) 
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.ControllerName = "Function2";
    var app = angular.module("myApp", []); // creating a APP     app.controller("Function1", Function1); // Registering the VM     app.controller("Function2", Function2);


Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.

<body ng-app="myApp" id=1>
   Global value is {{Counter}}<br />
<div ng-controller="Function1">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function1">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.

Do I need Jquery for Angular?

No , you do not need Jquery for Angular. It’s independent of Jquery.

How is the data binding in Angular ?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

How do we make HTTP get and post calls in Angular?

To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.

function CustomerController($scope,$http)
	$scope.Add = function()
            $http({ method: "GET", url: "http://localhost:8438/SomeMethod"     }).success(function (data, status, headers, config)
                   // Here goes code after success 		}

“$http” service API needs atleast three things:-

  • First what is the kind of call “POST” or “GET”.
  • Second the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.
$http({ method: "GET", url: "http://localhost:8438/SomeMethod"    }).success(function (data, status, headers, config)
// Here goes code after success }

How do we pass data using HTTP POST in Angular ?

You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.

Var myData = {};
myData.CustomerName = &ldquo;Test&rdquo;;
$http({ method: "POST",
	data: myData,
	url: "http://www.xyz.com"})
	.success(function (data, status, headers, config)
	  // Here goes code after success 	}

What is dependency injection and how does it work in Angular?

Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.

For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.

function CustomerController($scope,$http)
// your consumer would be using the scope and http objects }

How does DI benefit in Angular?

There are two big benefits of DI: – Decoupling and Testing.

Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.

function FileLogger()
        this.Log = function () {
            alert("File logger");
function EventLogger()
        this.Log = function () {
            alert("Event viewer logger");

Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.

function Customer($scope, Logger)
        $scope.Logger = {};
        if (config.Loggertype = "File")
            $scope.Logger = new FileLogger();
            $scope.Logger = new EventLogger();

But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.

function Customer($scope,$http, Logger)
        $scope.Logger = Logger;

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.

What are services in Angular?

Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.

function Customer($scope,$http, Logger)
        $scope.Logger = Logger;

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

var app = angular.module("myApp", []); // creating a APP app.controller("Customer", Customer); // Registering the VM app.service("Logger", EventLogger); // Injects a global Event logger object 

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Are Service object instances global or local?

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

function HitCounter()
       var i = 0;
        this.Hit = function ()

This “HitCounter” class object is injected in “MyClass” class as shown in the below code.

function MyClass($scope, HitCounter)
	$scope.HitCounter = HitCounter;

Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.

var app = angular.module("myApp", []); // creating a APP app.controller("MyClass", MyClass); // Registering the VM app.service("HitCounter", HitCounter); // Injects the object 

Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.

So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.

When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

What is a Factory in Angular?

“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.

Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.

For example see the below code we have a “Customer”, “Phone” and “Address” class.

function Customer()
        this.CustomerCode = "1001";
        this.CustomerName = "Shiv";
function Phone()
        this.PhoneNumber = "";
function Address()
        this.Address1 = "";
        this.Address2 = "";

So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
  • Or must be we would like to create “Customer” object with “Phone” objects inside it.
  • Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.

So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

var add = new Address();
return add;
var phone =  new Phone();
return phone;

Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.

In the below factory you can see we have three functions:-

  • “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.
function CreateCustomer() {

return {
CreateWithAddress: function () {
varcust = new Customer();
cust.Address = CreateAddress();
CreateWithPhone: function () {
varcust = new Customer();
cust.Phone = {};
cust.Phone = CreatePhone();
CreateWithPhoneAddress: function () {
varcust = new Customer();
cust.Phone = CreatePhone();
cust.Address = CreateAddress();

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.

functionCustomerController($scope, Customerfactory)

        $scope.Customer = {};
        $scope.Init = function(TypeofCustomer)

if (TypeofCustomer == "1")
                $scope.Customer = Customerfactory.CreateWithAddress();
if (TypeofCustomer ==  "2")
                $scope.Customer = Customerfactory.CreateWithPhone();
if (TypeofCustomer == "3") {
                $scope.Customer = Customerfactory.CreateWithPhoneAddress();

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

var app = angular.module("myApp", []); // creating a APP app.controller("CustomerController", CustomerController); // Register the VM app.factory("Customerfactory", CreateCustomer);

So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

app.service("Logger", Logger); // Injects a global object

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app.factory("Customerfactory", CreateCustomer);

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

Factory Service
Usage When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

My other interview question articles

jQuery, JSON and Less Interview questions with answers


100 important ASP.NET MVC interview questions


HTML 5 Interview questions with answers


WPF interview questions with answers



精通 MEAN: MEAN 堆栈

在 2002 年的一本著作中,David Weinberger 将发展迅速的 Web 内容描述成一个 小块松散组合(Small Pieces                    Loosely Joined)。这个比喻让我印象深刻,因为大家一般很容易认为 Web                 是一个巨大的技术堆栈。实际上,您访问的每个网站都是库、语言与 Web 框架的一种独特组合。

LAMP 堆栈 是早期表现突出的开源                 Web 技术集合之一:它使用 Linux® 作为操作系统,使用 Apache 作为 Web 服务器,使用 MySQL 作为数据库,并使用                 Perl(或者 Python 和 PHP)作为生成基于 HTML Web                 页面的编程语言。这些技术的出现并非为了一起联合工作。它们是独立的项目,由多位雄心勃勃的软件工程师前赴后继地整合在一起。自那以后,我们就见证了 Web                 堆栈的大爆发。每一种现代编程语言似乎都有一个(或两个)对应的 Web                 框架,可将各种混杂的技术预先组装在一起,快速而又轻松地创建一个新的网站。

MEAN 堆栈是 Web 社区中赢得大量关注和令人兴奋的一种新兴堆栈:MongoDBExpressAngularJSNode.js。MEAN 堆栈代表着一种完全现代的 Web                 开发方法:一种语言运行在应用程序的所有层次上,从客户端到服务器,再到持久层。本系列文章演示了一个 MEAN Web                 开发项目的端到端开发情况,但这种开发并不仅限于简单的语法。本文将通过作者的亲身实践向您深入浅出地介绍了该堆栈的组件技术,包括安装与设置。参见 下载 部分,以便获取示例代码。


在使用开源软件构建专业网站领域时,MEAN(MongoDB、Express、AngularJS 和 Node.js)堆栈是对流行已久的                     LAMP 堆栈的一个新兴挑战者。MEAN 代表着架构与心理模型(mental model)方面的一次重大变迁:从关系数据库到                     NoSQL,以及从服务器端的模型-视图-控制器到客户端的单页面应用程序。本系列文章将介绍 MEAN                     堆栈技术如何互补,以及如何使用堆栈创建二十一世纪的、现代的全堆栈 JavaScript Web 应用程序。

“实际上,您访问的每个网站都是库、语言与 Web 框架的独特组合。”



MEAN 不仅仅是一次首字母缩写的简单重新安排与技术升级。将基础平台从操作系统 (Linux) 转变为 JavaScript 运行时                 (Node.js) 让操作系统变得独立:Node.js 在 Windows® 与 OS X 上的运行情况和在 Linux 上一样优秀。

Node.js 同样取代了 LAMP 堆栈中的 Apache。但 Node.js 远远不止是一种简单的 Web                 服务器。事实上,用户不会将完成后的应用程序部署到单机的 Web 服务器上;相反,Web 服务器已经包含在应用程序中,并已在 MEAN                 堆栈中自动安装。结果,部署过程得到了极大简化,因为所需的 Web 服务器版本已经与余下的运行时依赖关系一起得到了明确定义。

不仅是 MEAN

尽管本系列文章重点讲述的是 MEAN 太阳系中的四大行星,但也会介绍 MEAN 堆栈中的一些较小的(但并非不重要的)卫星类技术:

从传统数据库(如 MySQL)到 NoSQL,再到无架构的、以文档为导向的持久存储(如                 MongoDB),这些代表着持久化策略发生了根本性的转变。用户花费在编写 SQL 上的时间将会减少,将会有更多的时间编写 JavaScript                 中的映射/化简功能。用户还能省掉大量的转换逻辑,因为 MongoDB 可以在本地运行 JavaScript Object Notation                    (JSON)。因此,编写 RESTful Web 服务变得前所未有的容易。

但从 LAMP 到 MEAN 的最大转变在于从传统的服务器端页面生成变为客户端 单页面应用程序                     (SPA)。借助 Express 仍然可以处理服务器端的路由与页面生成,但目前的重点在客户端视图上,而 AngularJS                 可以实现这一点。这种变化并不仅仅是将 模型-视图-控制器 (MVC)                 工件从服务器转移到客户端。用户还要尝试从习惯的同步方式转而使用基本由事件驱动的、实质上为异步的方式。或许最重要的一点是,您将从以页面为中心的应用程序视图转到面向组件的视图。

MEAN 堆栈并非以移动为中心,AngularJS                 在桌面电脑、笔记本电脑、智能手机、平板电脑和甚至是智能电视上的运行效果都一样,但它不会把移动设备当作二等公民对待。而且测试事后不再是问题:借助世界级的测试框架,比如                     MochaJSJasmineJSKarmaJS,您可以为自己的 MEAN                 应用程序编写深入而又全面的测试套件。

准备好获得 MEAN 了吗?


安装 Node.js

您需要安装 Node.js,以便在本系列中的示例应用程序上工作,如果尚未安装它,那就立刻开始安装吧。

如果使用 UNIX® 风格的操作系统(Linux、Mac OS X 等),我推荐使用 Node Version Manager                    (NVM)。(否则,在 Node.js 主页上单击                     Install,下载适合您操作系统的安装程序,然后接受默认选项即可。)借助 NVM,您可以轻松下载                 Node.js,并从命令行切换各种版本。这可以帮助您从一个版本的 Node.js 无缝转移到下一版本,就像我从一个客户项目转到下一个客户项目一样。

NVM 安装完毕后,请输入命令 nvm ls-remote 查看哪些 Node.js 版本可用于安装,如清单 1 中所示。

清单 1. 使用 NVM 列出可用的 Node.js                 版本
$ nvm ls-remote



输入 nvm ls 命令可以显示本地已经安装的 Node.js 版本,以及目前正在使用中的版本。

在撰写本文之际,Node 网站推荐 v0.10.28 是最新的稳定版本。输入 nvm install v0.10.28                 命令在本地安装它。

安装 Node.js 后(通过 NVM 或平台特定的安装程序均可),可以输入 node --version                 命令来确认当前使用的版本:

$ node --version



什么是 Node.js?

Node.js 是一种 headless JavaScript 运行时。它与运行在 Google Chrome 内的 JavaScript                 引擎(名叫 V8)是一样的,但使用 Node.js 可以从命令行(而非浏览器)运行 JavaScript。


熟悉自己所选浏览器中的开发人员工具。我将在整个系列中通篇使用 Google Chrome,但用户可以自行选择使用 Firefox、Safari                     或者甚至是 Internet Explorer。

  • 在 Google Chrome 中,单击 Tools > JavaScript                            Console
  • 在 Firefox 中,单击 Tools > Web Developer > Browser                            Console
  • 在 Safari 中,单击 Develop > Show Error                        Console。(如果看不到 Develop 菜单,可以在 Advanced preferences 页面上单击                             Show Develop menu in menu bar。)
  • 在 Internet Explorer 中,单击 Developer Tools > Script >                            Console

我曾有些学生嘲笑过从命令行运行 JavaScript 的主意:“如果没有要控制的 HTML,那 JavaScript 还有什么好处呢?”                 JavaScript 是在浏览器(Netscape Navigator 2.0)中来到这个世界的,因此那些反对者的短视和天真是可以原谅的。

事实上,JavaScript 编程语言并未针对 文档对象模型 (DOM) 操作或形成 Ajax 请求提供本地功能。该浏览器提供了 DOM API,可以方便用户使用                 JavaScript 来完成这类工作,但在浏览器之外的地方,JavaScript 不具备这些功能。

下面给出了一个例子。在浏览器中打开一个 JavaScript 控制台(参见 访问浏览器的开发人员工具)。输入 navigator.appName。获得响应后,请输入                 navigator.appVersion。得到的结果类似于图 1 中所示。

图 1. 在 Web 浏览器中使用 JavaScript navigator                     对象

在 Web 浏览器中使用 navigator JavaScript 对象的屏幕截图

在图 1 中,Netscape 是对 navigator.appName 的响应,而对                 navigator.appVersion 的响应则是经验丰富的 Web                 开发人员已经熟知但爱恨不一的、神秘的开发人员代理字符串。在图 1 中(截自 OS X 上的 Chrome 浏览器),该字符串是                 5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36

现在,我们要创建一个名为 test.js 的文件。在文件中输入同样的命令,并将每个命令包含在 console.log()                 调用中:


保存文件并输入 node test.js 来运行它,如清单 2 中所示。

清单 2. 查看 Node.js 中的                     navigator is not defined 错误
$ node test.js 

ion (exports, require, module, __filename, __dirname) { console.log(navigator.
ReferenceError: navigator is not defined
    at Object.<anonymous> (/test.js:1:75)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

正如您看到的那样,navigator 在浏览器中可用,但在 Node.js 中不可用。(不好意思,让您的第一个                 Node.js 脚本失败了,但我想确保让您相信,在浏览器中运行 JavaScript 与在 Node.js 中运行它是不同的。)

根据堆栈跟踪的情况,正确的 Module 没有得到加载。(Modules 是在浏览器中运行 JavaScript 与在                 Node.js 中运行它之间的另一主要区别。我们将立刻讲述 Modules 的更多相关内容。)为了从 Node.js 获得类似的信息,请将                 test.js 的内容修改为:


再次输入 node test.js,可以看到类似于清单 3 中的输出。

清单 3. 在 Node.js                 中使用过程模块
$ node test.js

{ http_parser: '1.0',
  node: '0.10.28',
  v8: '',
  ares: '1.9.0-DEV',
  uv: '0.10.27',
  zlib: '1.2.3',

  modules: '11',
  openssl: '1.0.1g' }

在 Node.js 中成功运行第一个脚本之后,我们将接触下一个主要概念:模块。



可以在 JavaScript 中创建单一功能的函数,但与在 Java、Ruby 或 Perl 中不同,无法将多个函数打包到一个能够导入导出的内聚模块或                 ”包“ 中。当然,使用 <script> 元素可以包含任意 JavaScript                 源代码文件,但这种历史悠久的方法在两个关键方面缺少正确的模块声明。

首先,使用 <script> 元素包含的任意 JavaScript                 将被加载到全局命名空间中。使用模块可以导入的函数被封装在一个局部命名的变量中。其次,同时更为关键的是,可以使用模块显式地声明依赖关系,而使用                 <script> 元素则做不到这一点。结果,导入 Module A 时也会同时导入依赖的 Modules B                 和 C。当应用程序变得复杂时,传递依赖关系管理很快将成为一种关键需求。


顾名思义,CommonJS 项目定义了一种通用的模块格式(包括其他浏览器之外的 JavaScript 规范)。Node.js 属于众多非官方的                     CommonJS 实现之一。RingoJS (类似于 Node.js 的一种应用服务器,运行在 JDK 上的 Rhino/Nashorn                    JavaScript 运行时之上) 基于 CommonJS,流行的 NoSQL 持久存储 CouchDB 和 MongoDB 也是如此。

模块是用户衷心期盼的下一 JavaScript 主要版本 (ECMAScript 6) 的功能,但直到该版本被广泛接受之前,Node.js                 目前使用的是它自己基于 CommonJS                 规范的模块版本。

使用 require 关键字可以在脚本中包含 CommonJS 模块。例如,清单 4 是对 Node.js 主页上的                 Hello World 脚本稍微进行修改后的版本。创建一个名为 example.js 的文件,并将清单 4 中的代码复制到其中。

清单 4. Node.js 中的 Hello                World
var http = require('http');
var port = 9090;
console.log('Server running at' + port + '/');

function responseHandler(req, res){
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('<html><body><h1>Hello World</h1></body></html>');

输入 node example.js 命令运行新的 Web 服务器,然后在 Web 浏览器中访问

看一看清单 4 中的头两行。您很可能写过几百次(或几千次)像 var port = 9090;                 这样的简单语句。这条语句定义了一个名为 port 的变量,并将数字 9090 赋值给它。第一行                 (var http = require('http');) 用于导入一个 CommonJS 模块。它引入                 http 模块并将它指派给一个局部变量。 and assigns it to a local variable. All                of the corresponding modules that http 依赖的所有对应模块也同时被                 require 语句导入。

example.js 后面的代码行:

  1. 创建一个新的 HTTP 服务器。
  2. 指定一个函数来处理响应。
  3. 开始监听指定端口上进入的 HTTP 请求。

这样通过寥寥几行 JavaScript 代码,就可以在 Node.js 中创建了一个简单的 Web                 服务器。在本系列随后的文章中您会看到,Express 将这个简单的例子被扩展用于处理更为复杂的路由,同时还将提供静态与动态生成的资源。

http 模块是 Node.js 安装的标准组件之一。其他标准的 Node.js 模块还支持文件                 I/O,读取来自用户的命令行输入,处理底层的 TCP 和 UDP 请求等等。访问 Node.js 文档的 Modules                 部分,查看标准模块的完整列表并了解它们的功能。



什么是 NPM?

NPM 是 Node Packaged Modules 的简写。要查看包含超过 75,000 个公用第三方 Node 模块的清单,请访问 NPM 网站。在网站上搜索 yo                 模块。图 2 显示了搜索结果。

图 2. yo 模块的详细情况

显示了 yo 模块的详细信息的 NPM 搜索结果的屏幕截图

结果页面简要介绍了该模块(搭建 Yeoman 项目的 CLI                 工具),并显示它在过去一天、一周和一月内被下载的次数、编写该模块的作者、它依赖于哪些其他的模块(如果存在)等内容。最重要的是,结果页面给出了安装该模块的命令行语法。

要从命令行获取关于 yo 模块的类似信息,请输入 npm info yo                 命令。(如果您还不知道模块的官方名称,可以输入 npm search yo 来搜索名称中包含字符串                 yo 的所有模块。)npm info 命令显示模块的 package.json 文件的内容。

了解 package.json

每个 Node.js 模块都必须关联一个格式良好的 package.json 文件,因此,熟悉此文件的内容是值得的。清单 5、清单 6 和清单 7 分三部分显示了                 yo 模块的 package.json 文件的内容。

如清单 5 中所示,第一个元素通常是 namedescription 和一个可用                 versions 的 JSON 数组。

清单 5. package.json,第 1                 部分
$ npm info yo

{ name: 'yo',
  description: 'CLI tool for scaffolding out Yeoman projects',
  'dist-tags': { latest: '1.1.2' },
     '1.1.2' ],

要安装一个模块的最新版本,请输入 npm install package 命令。输入                 npm install package@version 可以安装一个特定的版本。

如清单 6 中所示,接下来将显示作者、维护者和可以直接查找源文件的 GitHub 库。

清单 6. package.json,第 2                 部分
author: 'Chrome Developer Relations',
 { type: 'git',
   url: 'git://github.com/yeoman/yo' },
homepage: 'http://yeoman.io',
 [ 'front-end',
   'stack' ],

在这个例子中,还可以看到一个指向项目主页的链接和一个相关关键字的 JSON 数组。并非所有 package.json                 文件中都会出现所有这些字段,但用户很少会抱怨与一个项目相关的元数据太多。

最后,清单 7                 中列出了附有显式版本号的依赖关系。这些版本号符合主版本.次版本.补丁版本的常用模式,被称为                     SemVer(语义版本控制)。

清单 7. package.json,第 3                 部分
engines: { node: '>=0.8.0', npm: '>=1.2.10' },
 { 'yeoman-generator': '~0.16.0',
   nopt: '~2.1.1',
   lodash: '~2.4.1',
   'update-notifier': '~0.1.3',
   insight: '~0.3.0',
   'sudo-block': '~0.3.0',
   async: '~0.2.9',
   open: '0.0.4',
   chalk: '~0.4.0',
   findup: '~0.1.3',
   shelljs: '~0.2.6' },
 { 'grunt-cli': '~0.1.7',
   bower: '>=0.9.0' },
 { grunt: '~0.4.2',
   mockery: '~1.4.0',
   'grunt-contrib-jshint': '~0.8.0',
   'grunt-contrib-watch': '~0.5.3',
   'grunt-mocha-test': '~0.8.1' },

这个 package.json 文件表明,它必须安装在 0.8.0 或更高版本的 Node.js 实例上。如果试图使用                 npm install 命令安装一个不受支持的版本,那么安装将会失败。

SemVer 的快捷语法

清单 7 中,您会注意到,很多依赖关系版本中都有一个波浪符号 (~)。这个符号相当于                     1.0.x(也属于有效语法),意思是 ”主版本必须是 1,次版本必须是 0,但您可以安装所能找到的最新补丁版本“。SemVer                         中的这种隐含表达法意味着,补丁版本绝不会 对 API                     做出重大修改(通常是对现有功能的缺陷修复),而次版本会在不打破现有功能的情况下引入另外的功能(比如新的函数调用)。

除了平台要求之外,这个 package.json 文件还提供几个依赖关系列表:

  • dependencies 部分列出了运行时的依赖关系。
  • devDependencies 部分列出了开发过程中需要的模块。
  • peerDependencies 部分支持作者定义项目之间的 ”对等“                     关系。这种功能通常用于指定基础项目与其插件之间的关系,但在这个例子中,它指出了包含 Yeoman 项目与 Yo 的其他两个项目(Grunt                     与 Bower)。

如果在不指定模块名的情况下输入 npm install 命令,那么 npm 会访问当前目录中的                 package.json 文件,并安装我刚刚讨论过的三部分内容中列出的所有依赖关系。

安装一个能正常工作的 MEAN 堆栈,下一步是安装 Yeoman 与相应的 Yeoman-MEAN 生成器。


安装 Yeoman

作为一名 Java 开发人员,我无法想象在没有诸如 Ant 或 Maven 这样的编译系统的情况下如何启动一个新项目。类似地,Groovy 和                 Grails 开发人员依靠的是 Gant(Ant 的一种 Groovy 实现)或                 Gradle。这些工具可以搭建起一个新的目录结构,动态下载依赖关系,并准备好将项目发布。

在纯粹的 Web 开发环境中,Yeoman 可以满足这种需要。Yeoman 是三种 Node.js 工具的集合,包括用于搭建的纯 JavaScript                 工具 Yo,管理客户端依赖关系的 Bower,以及准备项目发布的 Grunt。通过分析 清单 7                 可以得出这样的结论:安装 Yo 时也会安装它对等的 Grunt 和 Bower,这要感谢 package.json 中的                 peerDependencies 部分。

通常,输入 npm install yo --save 命令可以安装 yo 模块并更新                 package.json 文件中的 dependencies                 部分。(npm install yo --save-dev 用于更新                 devDependencies 部分。)但这三个对等的 Yeoman                 模块算不上是特定于项目的模块,它们是命令行实用工具,而非运行时依赖关系。要全局安装一个 NPM 包,需要在 install                 命令后增加一个 -g 标志。

在系统上安装 Yeoman:

npm install -g yo

在完成包安装后,输入 yo --version 命令来验证它已经在运行中。

Yeoman 与基础架构的所有余下部分都准备就绪后,便可以开始安装 MEAN 堆栈了。


安装 MeanJS

您可以手动安装 MEAN 堆栈的每一部分,但需要十分小心。谢天谢地,Yeoman 通过其 generators(生成器)                提供了一种更轻松的安装方式。

Yeoman 生成器就是引导一个新 Web                 项目更轻松的方式。该生成器提供了基础包及其所有依赖关系。此外,它通常还会包含一个工作的编译脚本及其所有相关插件。通常,该生成器还包含一个示例应用程序,包括测试在内。

Yeoman 团队构建和维护了几个 “官方的”                     Yeoman 生成器社区驱动的 Yeoman 生成器(超过 800 个)远远超过官方生成器的数量。

您将用于引导第一个 MEAN 应用程序的社区生成器被称为 MEAN.JS,这也在意料之中。

在 MEAN.JS 主页上,单击 Yo Generator 菜单选项或者直接访问 Generator 页面,图 3                 中显示了其中的一部分。

图 3. MEAN.JS Yeoman 生成器

MEAN.JS Yeoman 生成器页面的屏幕截图

该页面上的说明指出要首先 Yeoman,这一点您已经完成。下一步是全局安装 MEAN.JS 生成器:

npm install -g generator-meanjs

生成器准备就绪后,便可以开始创建您的第一个 MEAN 应用程序了。创建一个名为 test 的目录,使用 cd                 命令进入它,然后输入 yo meanjs 命令生成应用程序。回答最后两个问题,如清单 8                 中所示。(您可以为开始四个问题提供自己的答案。)

清单 8. 使用 MEAN.JS Yeoman                generator
$ mkdir test
$ cd test
$ yo meanjs

    |       |
    |--(o)--|   .--------------------------.
   `---------�  |    Welcome to Yeoman,    |
    ( _�U`_ )   |   ladies and gentlemen!  |
    /___A___\   '__________________________'
     |  ~  |
 �   `  |� � Y `

You're using the official MEAN.JS generator.
[?] What would you like to call your application? 
[?] How would you describe your application? 
Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js
[?] How would you describe your application in comma separated key words?
MongoDB, Express, AngularJS, Node.js
[?] What is your company/author name? 
Scott Davis
[?] Would you like to generate the article example CRUD module? 
[?] Which AngularJS modules would you like to include? 
ngCookies, ngAnimate, ngTouch, ngSanitize

在回答最后一个问题后,您会看到一系列行为,这是 NPM 在下载所有服务器端的依赖关系(包括 Express)。NPM 完成后,Bower                 将下载所有客户端的依赖关系(包括 AngularJS、Bootstrap 和 jQuery)。

至此,您已经安装了 EAN 堆栈(Express、AngularJS 和 Node.js) — 目前只缺少 M                (MongoDB)。如果现在输入 grunt 命令,在没有安装 MongoDB 的情况下启动应用程序,您会看到类似于清单                 9 中的一条错误消息。

清单 9. 试图在没有 MongoDB 的情况下启动                 MeanJS
        throw er; // Unhandled 'error' event
Error: failed to connect to [localhost:27017]
    at null.<anonymous> 

[nodemon] app crashed - waiting for file changes before starting...

如果启动应用程序时看到这条错误消息,请按下 Ctrl+C 键停止应用程序。

为了使用新的 MEAN 应用程序,现在需要安装 MongoDB。


安装 MongoDB

MongoDB 是一种 NoSQL 持久性存储。它不是使用 JavaScript 编写的,也不是 NPM 包。必须单独安装它才能完成 MEAN                 堆栈的安装。

访问 MongoDB 主页,下载平台特定的安装程序,并在安装                 MongoDB 时接受所有默认选项。

安装完成时,输入 mongod 命令启动 MongoDB 守护程序。

MeanJS Yeoman 生成器已经安装了一个名为 Mongoose 的                 MongoDB 客户端模块,您可以检查 package.json 文件来确认这一点。我将在后续的文章中详细介绍 MongoDB 和                 Mongoose。

安装并运行 MongoDB 后,最终您可以运行您的 MEAN 应用程序并观察使用效果了。


运行 MEAN 应用程序

要启动新安装的 MEAN 应用程序,在运行 MeanJS Yeoman 生成器之前,一定要位于您创建的 test 目录中。在输入                 grunt 命令时,输出内容应该如清单 10 中所示。

清单 10. 启动 MEAN.JS                 应用程序
$ grunt

Running "jshint:all" (jshint) task
>> 46 files lint free.

Running "csslint:all" (csslint) task
>> 2 files lint free.

Running "concurrent:default" (concurrent) task
Running "watch" task
Running "nodemon:dev" (nodemon) task
[nodemon] v1.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: app/views/**/*.* gruntfile.js server.js config/**/*.js app/**/*.js
[nodemon] starting `node --debug server.js`
debugger listening on port 5858

 NODE_ENV is not defined! Using default development environment

MEAN.JS application started on port 3000

jshintcsslint                     模块(均由生成器进行安装)可以确保源代码在句法和语体上是正确的。nodemon                 包监控文件系统中的代码修改情况,并在检测到有的情况下自动重启服务器,当开发人员需要快速而频繁地修改代码基础时,这可以极大地提高他们的效率。(nodemon                 包只在开发阶段运行,要监测生产环境的变化,必须重新部署应用程序并重启 Node.js。)

按照控制台输出的提示,访问 http://localhost:3000                 并运行您的新 MEAN 应用程序。

图 4 显示了 MEAN.JS 示例应用程序的主页。

图 4. MEAN.JS 示例应用程序的主页

MEAN.JS 主页的屏幕截图

在菜单栏中单击 Signup 创建一个新的用户账号。现在填写 Sign-up 页面上的所有字段(如图 5                 中所示),然后单击 Sign up。在后续的指南中,您可以通过 Facebook、Twitter 等启用                 OAuth 登录

图 5. MEAN.JS 示例应用程序的 Sign-up 页面

MEAN.JS 示例应用程序的 Sign-up 页面的屏幕截图

现在,您的本地 MongoDB 实例中已经保存了一组用户证书,您可以开始撰写新的文章了。单击 Articles                 菜单选项(当您登录之后才会显示出来),并创建一些示例文章。图 6 显示了 Articles 页面。

图 6. MeanJS 的文章页面

MeanJS 文章页面的屏幕截图

您已经创建了自己的第一个 MEAN 应用程序。欢迎加入!


在这篇指南中,您完成相当多的内容。安装 Node.js 并编写了第一个 Node.js 脚本。学习了模块并使用 NPM 安装了几个第三方模块。安装                 Yeoman 并将它作为可靠的 Web 开发平台,其中包含一个搭建实用工具 (Yo),一个编译脚本                 (Grunt),以及一个管理客户端依赖关系的实用工具 (Bower)。安装 MeanJS Yeoman 生成器,并使用它来创建第一个 MEAN                 应用程序。安装 MongoDB 与 Node.js 客户端库 Mongoose。最后运行您的首个 MEAN 应用程序。

下一次,我们会详细了解示例应用程序的源代码,从而了解 MEAN 太阳系中的所有四颗行星 (MongoDB、Express、AngularJS 和                 Node.js)是如何相互作用的。



描述 名字 大小
样例代码 wa-mean1src.zip 1.38MB




  • 使用 Node.js、Express、AngularJS 和 MongoDB 构建一个实时投票应用程序”                 (developerWorks,2014 年 6 月):剖析一个在 IBM Bluemix™ 上部署的 MEAN                 开发项目。
  • 针对 Java 开发人员的 Node.js“(developerWorks,2011 年 11 月):介绍 Node.js                 并分析其事件驱动的并发性为何能引发用户广泛兴趣,甚至在死硬派 Java 开发人员中也是如此。
  • Node.js 起步(developerWorks,2014 年 1 月):查看这个时长 9 分钟的演示,其中快速介绍了                 Node.js 和 Express。
  • MongoDB:一种具有(所有正确的)RDBMS 行为的 NoSQL 数据库“(developerWorks,2010 年 9                 月):了解 MongoDB 的自定义 API、交互式 shell,以及对 RDBMS 样式的动态查询与快速简便的 MapReduce                 计算的支持。
  • 开始使用 JavaScript 语言“(developerWorks,2011 4 月和 8 月):在这篇由两部分组成的文章中学习                 JavaScript 的基础知识。
  • 针对 Java 开发人员的 JavaScript“(developerWorks,2011 年 4 月):分析                 JavaScript 为何是现代 Java 开发人员的重要工具的原因,并开始学习 JavaScript 变量、类型、函数和类。
  • LAMP 技术简介“(developerWorks,2005 年 5 月):将 MEAN                 与其以前的堆栈进行比较。
  • Mastering Grails(developerWorks, 2008-2009 年):查阅                 Scott Davis 撰写的关于 Grails (基于 Groovy 的 Web 开发框架)的系列文章。
  • 查看 HTML5 专题,了解更多和 HTML5 相关的知识和动向。
  • developerWorks Web development                专区:通过专门关于 Web 技术的文章和教程,扩展您在网站开发方面的技能。
  • developerWorks Ajax 资源中心:这是有关 Ajax 编程模型信息的一站式中心,包括很多文档、教程、论坛、blog、wiki 和新闻。任何 Ajax 的新信息都能在这里找到。