您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
Controller、常用依赖项
发布时间:2019-08-08 12:01:02编辑:雪饮阅读()
数据列表
<div ng-app='' ng-init="arr=[12,5,8,9,33]">
<li ng-repeat="item in arr">{{item}}</li>
</div>
数据列表-json对象
<div ng-app='' ng-init="json={a:'abc',b:55,c:99}">
<li ng-repeat="(key,value) in json">{{key}}={{value}}</li>
</div>
数据列表-json对象数组
<div ng-app='' ng-init="users=[{name:'dmj',age:18},{name:'xy',age:18}]">
<li ng-repeat="user in users">姓名:{{user.name}}年龄:{{user.age}}</li>
</div>
控制器
之前说ng的变量默认是不合js互通的,但是通过控制器可以实现,如下示例
<!DOCTYPE html>
<html ng-app='test'>
<head>
<title>angular</title>
<script type="text/javascript" src="angular.min.js"></script>
<script>
var app=angular.module('test',[]);
app.controller('zhangsan',function($scope){
$scope.a=12;
})
</script>
</head>
<body>
<div ng-controller="zhangsan">{{a}}</div>
</body>
</html>
示例中的$scope变量就是定义某个控制器的环境声明,则其的属性就可以在应用了该控制器的元素中使用
ng-controller:应用某个控制器
控制器(互通传统js方法)
<!DOCTYPE html>
<html ng-app='test'>
<head>
<title>angular</title>
<script type="text/javascript" src="angular.min.js"></script>
<script>
var app=angular.module('test',[]);
app.controller('zhangsan',function($scope){
$scope.alert=function(s){
window.alert(s);
};
})
</script>
</head>
<body>
<div ng-controller="zhangsan">
<input type="text" ng-model="str" />
<button ng-click="alert(str)">按钮</button>
</div>
</body>
</html>
控制器(自定义环境名)
默认控制器声明时固定环境名为$scope,控制器若要想修改默认的环境名,则也可以使用如下方式声明控制器
app.controller('zhangsan',['$scope','$http',function (a,b){
a.alert=function(s){
window.alert(s);
};
}]);
过滤器
控制器中声明:
$scope.items=[
{name:'2019春夏女装春雪纺衬衫t恤女',price:79,time:1565136129686},
{name:'花树果原创设计夏花女装2018新款连',price:469,time:1563236132686},
{name:'丁香娜2019秋装新款大码女装低圆领胖M',price:26,time:1565235629686}
];
模板中调用
<li ng-repeat="item in items">
<h3>{{item.name}}</h3>
<span>{{item.price|currency}}</span>
<span>{{item.time|date:"yyyy年MM月dd日"}}</span>
</li>日期过滤器
解析:
currency:货币过滤器
date: 日期过滤器
ng-hide
用ng-hide可非常简单的实现元素的显示与隐藏,如
<div ng-controller="zhangsan" ng-init='a=true;'>
<button ng-click='a=!a;'>显/隐</button>
<div style="background: pink;with:300px;height: 300px;" ng-hide='a'></div>
</div>
关键字词:angular,controller
上一篇:AngularJS基础及应用
下一篇:ajax数据交互、动画技术