項目中遇到個功能點,需要在ng-repeat循環完成後才能觸發,記錄下。
①書寫指令
//自定義repeat完成指令
app.directive('repeatFinish',function($timeout){
return {
restrict: 'A',
link: function(scope,elem,attr){
//當前循環至最後一個
if (scope.$last === true) {
$timeout(function () {
//向父控制器傳遞事件消息
scope.$emit('repeatFinishCallback');
},100);
}
}
}
});
②控制器中接收回調事件
//接收repeat完成事件
$scope.$on('repeatFinishCallback',function(){
//這裏寫repeat後需要進行的操作
//demo:獲取ul的高度
var ulH = document.getElementById('tagList').offsetHeight;
console.log('ul的高度:'+ ulH +'px');
});
③頁面中調用指令
<ul id="tagList">
<li ng-repeat="x in tagList" repeat-finish>{{x.name}}</li>
</ul>
拓展知識:$emit、$broadcast和$on是各個控制器間的通信手段。
- $emit 是由子控制器向父控制器發送事件與數據;
- $broadcast與$emit相反;
- $on是用於事件與數據的接收
附上完整的實例代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.tagBox{
width: 100px;
margin: 100px;
border: 1px solid #000;
}
ul{
overflow: hidden;
}
li{
float: left;
margin-right: 10px;
list-style: none;
}
</style>
</head>
<body ng-app="myApp" ng-controller="myController">
<div class="tagBox">
<ul id="tagList">
<li ng-repeat="x in tagList" repeat-finish>{{x.name}}</li>
</ul>
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('myApp',[]);
//自定義repeat完成指令
app.directive('repeatFinish',function($timeout){
return {
restrict: 'A',
link: function(scope,elem,attr){
//當前循環至最後一個
if (scope.$last === true) {
$timeout(function () {
//向父控制器傳遞事件消息
scope.$emit('repeatFinishCallback');
},100);
}
}
}
});
//控制器
app.controller('myController',function($scope){
$scope.tagList = [{
id: 1,
name: '蘋果'
},{
id: 2,
name: '香蕉'
},{
id: 3,
name: '橘子'
}];
//接收repeat完成事件
$scope.$on('repeatFinishCallback',function(){
//這裏寫repeat後需要進行的操作
//demo:獲取ul的高度
var ulH = document.getElementById('tagList').offsetHeight;
console.log('ul的高度:'+ ulH +'px');
});
});
</script>
</body>
</html>