Angular指令
常用指令
-
ng-app
:指定模块名,angular管理的区域
-
ng-model
:双向绑定
-
ng-init
:初始化数据
-
ng-click
:调用作用域对象的方法(点击时),值为函数调用,可以传$event
-
ng-controller
:指定控制器构造函数名,内部会自动创建一个新的子作用域
-
ng-bind
:解决使用{{}}显示数据闪屏(在很短时间内显示{{}})
-
ng-repeat
:遍历数组显示数据, 数组有几个元素就会产生几个新的作用域。在产生的作用域中自动注入以下几个属性:$index
,$first
, $last
, $middle
, $odd
, $even
-
ng-show
:布尔类型, 为true显示
-
ng-hide
:布尔类型, 为true隐藏
-
ng-class
:动态引用定义的样式 {aClass: true, bClass: false}
- ng-class可以是一个js对象
- js对象拥有多个属性,表明可能会使用多个class,是否会使用根据属性值判断
- js对象的属性名为class名称,属性值为true时,表示使用该class,否则不使用
-
ng-style
:动态引用通过js指定的样式对象 {color:'red', background:'blue'}
- ng-style可以是一个js对象
- js对象的每一个属性名/属性值对,表示一条样式声明
- 注意属性值的引号问题
-
ng-mouseenter
:鼠标移入监听, 值为函数调用, 可以传$event
-
ng-mouseleave
:鼠标移出监听, 值为函数调用, 可以传$event
举个栗子
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.odd{
background-color: skyblue;
}
.even{
background-color: deeppink;
}
</style>
</head>
<body ng-app="myApp">
<div ng-controller="Ctrl">
<div>
<h2>价格计算器(自动)</h2>
数量:<input type="number" ng-model="count1">
价格:<input type="number" ng-model="price1">
<p>总计: {{count1 * price1}}</p>
</div>
<div>
<h2>价格计算器(手动)</h2>
数量:<input type="number" ng-model="count2">
价格:<input type="number" ng-model="price2">
<button ng-click="getTotalPrice()">计算</button>
<p>总计: {{totalPrice}}</p>
</div>
<div>
<h2>用户信息</h2>
<ul>
<li ng-repeat="p in persons">{{$index}}--{{p.name}}--{{$odd}}--{{$even}}</li>
</ul>
</div>
<div>
<h2>ng-bind</h2>
<p>{{213}}</p>
<p ng-bind="123"></p>
</div>
<div>
<h2>ng-show/hide</h2>
<button ng-click="switchShow($event)">切换显示</button>
<p ng-show="show">正面</p>
<p ng-hide="show">反面</p>
</div>
<div>
<h2>ng-mouseenter/mouseleave</h2>
<div style="width: 100px; height: 100px;" ng-style="bgc"
ng-mouseenter="me()" ng-mouseleave="ml()"></div>
</div>
<div>
<h2>ng-style</h2>
<ul>
<li ng-class="{odd: $odd, even: $even}" ng-repeat="p in persons">{{p.name}}</li>
</ul>
</div>
</div>
<script type='text/javascript' src='../../js/angular-1.5.5/angular.js'></script>
<script type='text/javascript'>
angular.module('myApp', [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.price1 = 1;
$scope.count1 = 20;
$scope.price2 = 2;
$scope.count2 = 25;
$scope.totalPrice = $scope.price2 * $scope.count2;
$scope.getTotalPrice = function () {
$scope.totalPrice = $scope.price2 * $scope.count2;
}
$scope.persons = [
{name: 'a1', age: 22},
{name: 'a2', age: 22},
{name: 'a3', age: 22},
{name: 'a4', age: 22},
{name: 'a5', age: 22}
];
$scope.show = true;
$scope.switchShow = function ($event) {
console.log($event);
$scope.show = !$scope.show;
}
$scope.bgc = {background: 'skyblue'};
$scope.me = function () {
$scope.bgc.background = 'deeppink';
}
$scope.ml = function () {
$scope.bgc.background = 'skyblue';
}
}]);
</script>
</body>
</html>