2018/8/25 学习开始
ng-app="":初始化angular.js的管辖范围可以命名区域
要angular起作用 ng-app中必须要注明,可以留空。
为angular注明管理范围
<div ng-app=""></div>
<body ng-app=""></body>
ng-init初始化数据,初始化后数据对整个页面可见。
<body ng-app="test" >
<div ng-init="num=0"></div>
<input ng-model="num" >
<div>{{num}}</div>
</body>
<div>{{num}}</div>
以上结果所有位置输出都是0
循环
<div ng-repeat="v in array"></div>
绑定数据
对于输入框而言
<body ng-app="test" >
<input ng-model="num">
<div>{{num}}</div>
</body>
num就会跟随输入框的值变化而变化
ng-controller
app = angular.module("name0",{]);
app.controller("ctrl1" ,function($scope){
$scope.num=0;
})
<body ng-app="name0" ng-controller="ctrl1">
<input type="text" ng-model="num">
{{num}}
</body>
controller将Num初始化为0,然后Num会跟随输入框内容的变化而变化。
深度监视:
$scope.$watch('arr',function(){
...
},true);//最后一个参数起深度监视的作用
数据交互
a.php
<?php
echo $_GET['a']+$_GET['b'];
?>
html
app = angular.moduel("name0",{]);
app.controller("ctrl1" ,function($scope){
$scope.num=0;
$http.get('a.php',{params:{a:12,b:5}}.success(function(result){
alert('成功了');
})).error(function(){
alert('失败了');
})
})
<body ng-app="name0">
</body>
在新版本中http请求使用then来传递回掉。方便管理
$http.get(...).then(function(res){},function(){})
timeout:
var timer = $timeout(function(){
$scope.a+=2;
},2000);
//等待两秒后执行代码
apply(和watch一起使用)
$scope.$apply();
//强制数据更新
请求数据
$http.get(url,params:{}.success(function(){}).error(function(){}))
$http.post(url,params:{}.success(function(){}).error(function(){}))
$http.jsonp(url,params:{}.success(function(){}).error(function(){}))
jsonp 请求:wd=,cb=用于请求JSON数据。
2018/8/26更新
filter-过滤器
输出数据之前处理一下
<div ng-repeat = “v in arr”>{{v|currency}}</div>
<div ng-repeat = “v in arr”>{{v|date:"yyyy年MM月dd日 HH:mm:ss"}}</div>
自定义过滤器:
app.filter("名字",function(){
//初始化部分
return function(input){
//处理部分
return 'aaa';
}
})
2018/8/28更新
指令
功能:自定义标签,自定义组件
restrict:
E Element 标签
A Attribute属性
C Class 类
M Comment 备注
template:
内容用法:
app.directive('名字',function(){
json = {
restrict:'A',
template:"<span>abc</span>"
}
return json;
})
占位符:transclude:true嵌入模式打开时
原始内容放在占位符里(<ng-transclude></ng-transclude>)
2018/9/21
前端路由
在angular中有一个前端路由机制,目的是减少对服务器的请求次数。
我们访问以下网站时
http://xxx.com/#!/first
http://xxx.com/#!/second
http://xxx.com/#!/third
首先,在对服务器请求时。请求的地址都是http://xxx.com/。控制显示方式的位置在本地。
导入路由模块:
app=angular.module("test",['ngRoute']);
使用$routeProvider.when来注明URL和显示区域的关系
angular.module('routingDemoApp',['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/',{template:'这是首页页面'})
.when('/computers',{template:'这是电脑分类页面'})
.when('/printers',{template:'这是打印机页面'})
.otherwise({redirectTo:'/'});
加一个
<div ng-view></div>
当我们访问以下链接时,ng-view的位置就会出现对应template中的内容。
按钮触发事件 ng-click的用法:
$scope.a=function(){
...
}
然后在需要的位置 ng-click = "a()"即可