在学习之前,需要html,css,js知识基础,最好知道自动化测试,BDD-行为驱动开发,TDD-测试驱动开发等概念,你可以不会jquery,php,或数据库。
angular可以帮你组织JS,创建响应式的网站,易于测试且能很好的和jquery结合,所以我们才使用它。
首先我们需要了解一些概念:
directive:就是一个标记,用来告诉angular运行或引用一些js代码,如:
<body ng-controller="StoreController"></body>
function StoreController(){
alert('Welcome to use angular");
}
现在开始实例,新建一个文件夹,准备bootstrap.min.css,angular.min.js。
新建一index.html:
<!DOCTYPE html>
<html lang="zh-cn" ng-app="gemStore">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-controller="StoreController as gemStore">
<h1>{{gemStore.product.name}}</h1>
<h2>
${{gemStore.product.price}}
</h2>
<p>
{{gemStore.product.description}}
</p>
</div>
<p>
I am {{4+6}}
</p>
<p>
{{"hello"+"you"}}
</p>
</body>
</html>
新建一个app.js:
(function(){
var app=angular.module('gemStore',[]);
var gem={
name:'Addidas的鞋子!',
price:2.95,
description:'some gems have hidden qualities beyond their luster,....Dodeca is one of those gems.'
};
app.controller('StoreController',function(){
this.product=gem;
});
})();
在chrome里打开index.html:
模型里的数据已经显示出来,我们并没有像使用jquery一样手动操作DOM来显示数据,而是加了一些angular的directive,实际上就是它识别的一些标签。
gemStore是模块名,StoreController是控制器,在html里我们定义了它们的有效范围,在子结点下就可以使用里面的方法或数据了。
this.product=gem;
这一句里的this指的是啥?在旧的版本里,我们有相$scope对象来指定要绑定的数据,这里我们用了this,让我们看下this是什么:
console.log(this);
this.product=gem;
它里面有product属性,还有一些继承过来的东西,根据作用域链来看,应该是app,也就是gemStore模块。