AngularJs自定义指令详解(7) - multiElement

时间:2021-10-21 16:21:37

multiElement不太常用,从下面这个例子可以大致看出它的作用:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="../lib/angular-1.3.16/angular.min.js"></script>
<script src=""></script>
<title></title>
<script language="JavaScript">
var app = angular.module("app", []);
app.directive('myDirective',function () {
return{
multiElement:true,
link:function(scope,element,attrs){
console.log(element);
}
};
});
</script>
</head>
<body ng-app="app">
<span my-directive-start></span>
<span my-directive-end></span>
</body>
</html>

在Chrome浏览器中审查元素,看看控制台输出:

AngularJs自定义指令详解(7) - multiElement

由此可知传给连接函数的element不是单个元素,而是3个,包括两个span和一个回车符。

实际上,我们把HTML代码改成:

<my-directive><span></span>
<span></span></my-directive>

控制台输出:

AngularJs自定义指令详解(7) - multiElement

这时候我们仍然可以在childNodes中找到它们。

所以把multiElement设为true的目的,仅仅是引入my-directive-start、my-directive-end这两个标记,在某些时候有利于我们书写。

现在看看AngularJs内置指令ngRepeat(可以使用ng-repeat-start和ng-repeat-end)类似的做法:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="../lib/angular-1.3.16/angular.min.js"></script>
<script src=""></script>
<title></title>
<script language="JavaScript">
var app = angular.module("app", []);
app.run(function ($rootScope) {
$rootScope.list = [{name: '张三', age: 26, gender: '男'}, {name: '李四', age: 24, gender: '男'}];
});
</script>
</head>
<body ng-app="app">
<table border="1">
<tbody>
<tr ng-repeat-start="l in list">
<td>{{l.name}}</td>
<td></td>
</tr>
<tr ng-repeat-end>
<td>{{l.age}}</td>
<td>{{l.gender}}</td>
</tr>
</tbody>
</table>
</body>
</html>

输出:

张三  
26
李四  
24

如果没有ng-repeat-start和ng-repeat-end,用ng-repeat输出上面的东西,很吃力。

我们在ng-repeat-start和ng-repeat-end之间可以任意胡来,例子:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="../lib/angular-1.3.16/angular.min.js"></script>
<script src=""></script>
<title></title>
<script language="JavaScript">
var app = angular.module("app", []);
app.run(function ($rootScope) {
$rootScope.list = [{name: '张三', age: 26, gender: '男'}, {name: '李四', age: 24, gender: '男'}];
});
</script>
</head>
<body ng-app="app">
<table border="1">
<tbody>
<tr ng-repeat-start="l in list">
<td>{{l.name}}</td>
</tr>
<tr>
<td>{{l.age}}</td>
</tr>

<tr ng-repeat-end>
<td>{{l.gender}}</td>
</tr>
</tbody>
</table>
</body>
</html>

输出:

张三
26
李四
24