一、angularJS简介
1、使用angularJS可以方便的进行dom元素的操作,而不需要进行一些较为复杂的监听类事件的注册·
2、使用方法:
其一:本地引用js文件:注意相对路径的书写就行了。
<script src="../js/angular.min.js"></script>
其二:使用内容分发网络(CDN)进行加载类库。
官方的类库地址是
<script src="http://code.angularjs.org/1.2.25/angular.min.js"></script>
,但是貌似不翻墙上不了。
二、MVC模式的使用
1、angularJS使用mvc的思想进行设计,使用module进行模型的绑定,在视图层上进行展示,使用controller进行DOM元素的控制。
2、api的展示:
2.1、ng-app
<html ng-app>
:整个html页面的所有dom元素都会被angularJS“控制”。
2.2、ng-module
<input ng-model="query">
表明这个input输入框中的内容和一个叫“query”的module进行“双向绑定”,所谓双向绑定,是指“dom元素的变化会引起代码中绑定的module的变化,同时,代码控制的module的变化也会引起展示层dom元素的变化”。
2.3、ng-bind
<h5 ng-bind="result"></h5>
这种绑定只是代码中module的变化会引起dom元素的变化,但是这种变化只有人为(代码)的进行控制,才会展示出来。譬如下面:
>
<input ng-model="first">
<input ng-model="second">
<hr/>
<h5 ng-bind="result"></h5>
<button ng-click="cala()">ee</button>
</body>赋予了点击事件的一个button,点击的时候进行cala计算,将结果赋给$scope.result,而这里将result和input标签进行绑定,既可以进行展示。和
ng-module
相较而言,ng-bind
更加注重一种数据的被动展示性,而ng-module
则注重实时更新的特性。
2.4、ng-controller
<body ng-app="app" ng-controller="Controller">
表明整个<body>
中的dom将由“controller”这个控制器进行控制。
标准的使用控制器的方法有两种:1、
function PhoneListCtrl($scope) {
$scope.phones = [
{"name": "Nexus S",
"snippet": "Fast just got faster with Nexus S.",
"age": 0},
{"name": "Motorola XOOM™ with Wi-Fi",
"snippet": "The Next, Next Generation tablet.",
"age": 1},
{"name": "MOTOROLA XOOM™",
"snippet": "The Next, Next Generation tablet.",
"age": 2}
];
$scope.orderProp = 'age';
}
在这个controller中,定义了“phones”这个数组,“orderProp”这个字符串常量。
2、var app=angular.module('app',[]);
app.controller('Controller',function($scope){
$scope.cala=function(){
$scope.hehe='hihihi';
var a=parseInt($scope.first,10);
var b=parseInt($scope.second,10);
$scope.result=a+b;
window.alert("sorry,you are wrong!")
}
});
这里先定义一个module是“app”,这样定义的好处是:可以反复使用,在不同的<div>
或者其他的需要使用这个module的标签中使用。 继而在这个module上面定义一个controller控制器。需要注意的是,这样定义的话,module和controller就分离了,比放在一个<body>
上定义一个controller,需要这样说明定义:
<body ng-app="app" ng-controller="Controller">
2.5、ng-change
当数据发生改变的时候,会触发这个
ng-change
所指示的函数的运行app.controller('StartUpController',function($scope){ $scope.start={hehe:0}; $scope.jisuan=function(){ $scope.start.haha=$scope.start.hehe*10; } });其中:dom元素是这样书写的:
<form ng-controller="StartUpController">
<input ng-change="jisuan()" ng-model="start.hehe">
<hr />
result:{{start.haha}}
</form>事实上,这种
ng-change
的也可以这样来做:
使用$scope.$watch
进行监控,类似于注册的一个监听器。