AngularJS的四大特征:
1、MVC模式
Angular遵循软件工程的MVC模式,并鼓励展现,数据,和逻辑组件之间的松耦合.通过依赖注入(dependency injection),Angular为客户端的Web应用带来了传统服务端的服务,例如独立于视图的控制。 因此,后端减少了许多负担,产生了更轻的Web应用。
Model:数据,其实就是angular变量($scope.XX);
View: 数据的呈现,Html+Directive(指令);
Controller:操作数据,就是function,数据的增删改查;
2、双向绑定
双向的数据绑定允许模型和视图之间的自动同步。AngularJS使得对DOM的操作不再重要并提升了可测试性。
3、依赖注入
对象在创建时,其依赖的对象由框架来自动创建并注入进来,其实就是最少知识法则;模块中所有的service和provider两类对象,都可以根据形参名称实现DI.
4、模块化设计
高内聚低耦合法则
1)官方提供的模块 ng、ngRoute、ngAnimate
2)用户自定义的模块 angular.module('模块名',[ ])
AngularJS的语法:
表达式:{{表达式 }}
指令ng-app:在网页加载完毕时会自动引导(自动初始化)应用程序。
指令ng-model:用于绑定变量,这样用户在文本框输入的内容会绑定到变量上,而表达式可以实时地输出变量。
指令ng-init:对变量初始化
控制器:
var app=angular.module('myApp',[]); //定义了一个叫myApp的模块
app.controller('myController',function($scope){ //定义控制器
$scope.add=function(){
return parseInt($scope.x)+parseInt($scope.y);
}
});
使用:<body ng-app="myApp" ng-controller="myController">
x:<input ng-model="x" > y:<input ng-model="y" > 运算结果:{{add()}}
说明:$scope,就是控制器与视图层之间交换数据的桥梁,ng-controller用于指定所使用的控制器。
事件指令:ng-click="add()"点击时触发控制器的某个方法。这个是最常用的
数据读取:ng-repeat
<tr ng-repeat="entry in list"> <td>{{entry }}</td></tr>
<tr ng-repeat="entry in list"> <td>{{entry.id}}</td></tr> 看到这个应该明白了吧
读取自定义controller中返回给list中的数据
下面讲讲在真实开发中的用法:
要用到的MVC分层开发的思想,以及Angular带给我们的便利
建立三个js文件:base.js service.js controller.js
base.js:
var app=angular.module('my',[]);
service.js:
app.service('indexService',function($http){
this.getAlluuu=function(){
return $http.get('getAlluuu');
}
});
app.service('sendCodeService',function($http){
this.sendSms=function(){
var mobile = angular.element('#phoneNum').val();
$http(
{
method: "POST",
data:{'mobile':mobile},
url:"sendSms",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function(obj) {
var str = [];
for (var s in obj) {
str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
}
return str.join("&");
}
}
).success(function (resp) {
if(resp){
alert("发送成功");
}
});
}
});
这里使用了get和post两种提交方式。post提交需要注意headers请求头的方式。还需要把表单序列化,要不然后台接收不到参数
controller.js:
app.controller('indexController' ,function($scope,indexService){
$scope.findAll=function(){
indexService.getAlluuu().success(
function(response){
$scope.list=response;
}
);
}
});
app.controller('sendCodeController' ,function($scope, sendCodeService){
$scope.sendSms=function(){
sendCodeService.sendSms();
}
});
总结:AngularJs是独立存在的,及时项目不管有多复杂,都可以随心所欲的插入进去。更加符合后台开发思想。AngularJs是在页面启动就会初始化,极大的优化了系统的操作性能。
更多Angular交流,QQ群:244284555