之前講到directive自定義指令渊鞋,但是實(shí)際上單純創(chuàng)建指令是沒什么卵用的投队。減少開發(fā)成本畜伐,需要使用控制器與自己制作的指令交互吗讶。
<div ng-app=“App” ng-controller=“Ctrl ”>
? ? <—自定義一個指令—>
? ? <test testdata=“{{data}}”></test>
</div>
<script>
var app=angular.module(“App”,[]);
? ? app.controller(“Ctrl”function(){
? ? ? ? ? $scope.data=“測試數(shù)據(jù)”;
? ? });
? ? app.directive(“test”,function(){
? ? ? ? ? ? return{
? ? ? ? ? ? ? restrict:”AE”,
? ? ? ? ? ? ? template:”<div>{{dirdata}}</div>”,
? ? ? ? ? ? ? link:function(scope,element,attrs){
? ? ? ? ? scope.dirdata=attrs.testdata? ? ?
? ? ? ? ? ? ? }
? ? ? ? ? ? }? ?
? ? });
</script>
結(jié)果輸出:測試數(shù)據(jù)
說明:我看了一個晚上才發(fā)現(xiàn)袖裕。原來directive的數(shù)據(jù)表達(dá)方式與controller所賦值的數(shù)據(jù)的表達(dá)根本都不同曹抬。很有趣,自定義兩個指令之后(一個A一個E)急鳄,$sope居然可以直接訪問自定義的標(biāo)簽和屬性谤民。
這里的原理是這樣的,
1.定義test指令疾宏,以屬性的方式創(chuàng)建數(shù)據(jù)容器张足。
2.通過controller來給原來的容器存放數(shù)據(jù)
3.實(shí)例化test和data指令,創(chuàng)建一個模版坎藐,用于以普通html元素渲染數(shù)據(jù)为牍。
4.因?yàn)闊o法直接用test標(biāo)簽渲染數(shù)據(jù)。所以岩馍,初始化好了的數(shù)據(jù)都需要放到模版中渲染碉咆。所以接下來就需要將指令中的數(shù)據(jù)賦值到模版中(使用directive配置項(xiàng)的“l(fā)ink”函數(shù))
注:link函數(shù):這個函數(shù)用于定義指令的行為,(僅限于指令內(nèi)部)