※ng-repeat
迴圈功能<html ng-app>
<script type="text/javascript" src="angular.js"></script>
<body>
<div ng-init="xxx=[1,2,3]">
<ul>
<li ng-repeat="x in xxx">
{{x}}
</li>
</ul>
</div>
<div ng-init="ooo=[
{o:'a',x:1},
{o:'b',x:2},
{o:'c',x:3}]">
<table border=1>
<tr>
<td ng-repeat="a in ooo">
{{a.o + '-' + a.x}}
</td>
</tr>
</table>
<table border=5>
<tr ng-repeat="a in ooo">
<td>
{{a.o + '-' + a.x}}
</td>
</tr>
</table>
</div>
</body>
</html>
※ng-repeat 看要針對哪一個標籤循環,就寫在哪裡,上面的例子有寫在 tr 和 td
※ng-repeat 配合 controller
<html ng-app='xxx'>
<script type="text/javascript" src="angular.js"></script>
<body>
<table border=1 ng-controller='ccc'>
<tr ng-repeat="list in lists">
<td>
{{list.o}} - {{list.x}}
</td>
</tr>
</table>
</body>
<script>
var app = angular.module("xxx", []);
app.controller('ccc', ($scope) => {
$scope.lists = [
{
o: 'a', x: 1
}, {
o: 'b', x: 2
}, {
o: 'c', x: 3
}
];
});
</script>
</html>
※注意 ng-controller 的宣告至少要在ng-repeat的上一層
※directive的Element、Attribute、Class
restrict有以下四種,可以合在一起E:Element
A:Attribute
C:Class
M:Comment
預設是AE,所以不寫restrict時,可以用在元素和屬性上
要注意取的名字在使用時是用駝峰命名,如smallApple,要使用時,就要用small-apple
以上大小寫都不能錯,如果大小寫錯了不會報錯,只是沒有作用而已
<html ng-app='xxx'>
<script type="text/javascript" src="angular.js"></script>
<body>
<div good-boy>div</div>
<good-boy>defined</good-boy>
<p class='good-boy'>p</p>
</body>
<script>
var app = angular.module("xxx", []);
app.directive("goodBoy", () => {
return {
restrict : "AEC",
template : '<h1>h</h1>'
};
});
</script>
</html>
※裡面還有一個「replace」的屬性,但不是給這三個值用的,是給下面的comment用的,但如果寫了而且給false不會有作用
但如果給true,有可能會報「Template for directive 'tag name' must have exactly one root element. 」的錯,那是因為template裡面的值至少要有一個頂層標籤,以這個例子就是<h1>
假設我的template只寫h,且replace給true,就會報這個錯
※div、good-boy、p 標籤裡的文字(div、defined、p),只有在angular 讀不到時才會顯示,一讀到一定是覆蓋
※directive 之 comment
<html ng-app='xxx'>
<script type="text/javascript" src="angular.js"></script>
<body>
<!-- directive: good-boy -->
content...
</body>
<script>
var app = angular.module("xxx", []);
app.directive("goodBoy", () => {
return {
restrict : "M",
replace : true,
template : '<h1>h1</h1>'
};
});
</script>
</html>
※replace是配合restrict為「M」時使用
※在html裡打上<!-- directive: 自定標籤名 -->後,不管replace給什麼,在原始檔裡都會顯示
※這裡的replace是要不要將註解的部分取代成template寫的東東,如給true就會在網頁顯示,但並不會將content...取代掉









