自定義指令(中)

簡介

? ? ? ? 上一節(jié)講了自定義指令的配置項(xiàng),這一節(jié)我們看下自定義指令的作用域,自定義指令在開發(fā)中對于功能的抽取有著至關(guān)重要的作用,努力加油吧!????

例子

? ? ? ? <div ng-app="myController">

? ? ? ? ? ? ? ? <h1>父級消息:{{msg}}</h1>

? ? ? ? ? ? ? ? <input type="text" ng-model="count" />

? ? ? ? ? ? ? ? <my-directive parent-msg="Angular" myname="AngularJs" pmsg2="{{msg}}" pmsg3="count" p-fun="fun(msg)"></my-directive>

????????</div>

? ? ? ? <script>

? ? ? ? ? ? ? ? var app = angular.module("myController", []);

? ? ? ? ? ? ? ? app.controller("myController",["$scope",function($scope){

? ? ? ? ? ? ? ? ? ? ? ? //angular會默認(rèn)創(chuàng)建一個指令作用域并原型式繼承父級作用域

? ? ? ? ? ? ? ? ? ? ? ? $scope.pmsg = "父消息";

? ? ? ? ? ? ? ? ? ? ? ? $scope.count = 0;

? ? ? ? ? ? ? ? ? ? ? ? $scope.fun = function(val) {

? ? ? ? ? ? ? ? ? ? ? ? ? ? console.log(val+"被觸發(fā)");

????????????????????????}

????????????????}]);

? ? ? ? ? ? ? ? app.directive("myDirective",function() {

? ? ? ? ? ? ? ? ? ? ? ? return {

? ? ? ? ? ? ? ? ? ? ? ? ? ? //scope:false,

? ? ? ? ? ? ? ? ? ? ? ? ? ? scope: {

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? parentMsg: "@",

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? myname:"@",

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? name:"@myname",//myname第二種寫法

? ??????????????????????????????pmsg2:"@",//拿到父級作用域的值

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pmsg3:"=",//雙向數(shù)據(jù)綁定

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pFun: "&"

????????????????????????????},

? ? ? ? ? ? ? ? ? ? ? ? ? ? template:`

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ????<div>

????????????????????????????????????????????<h1>自定義指令</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h2>繼承于父級作用域:{{pmsg}}</h2>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <input type="text" ng-model="msg" />

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h1>{{parentMsg}}</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h1>{{myname}}</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h1>{{name}}</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h1>{{pmsg2}}</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <h1>{{pmsg3}}</h1>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <input type="text" ng-model="pmsg3" >

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? <button ng-click="pFun({msg:parentMsg})">點(diǎn)擊</button>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? </div>

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? `

????????????????????????}

????????????????})

????????</script>

? ? ? ? scope: 如果scope指定為false,指令會繼承自己的父級作用域。(非常不嚴(yán)謹(jǐn),不建議使用),當(dāng)scope指定為true時,指令會創(chuàng)建自己的作用域,并繼承父級作用域。

? ? ? ? scope:{}當(dāng)scope為對象時,表明創(chuàng)建的是隔離作用域,這時候此作用域與其他作用域不產(chǎn)生依賴或影響(非常強(qiáng)大)

父子傳值:@


? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?不積跬步無以至千里,不積小流無以成江海 ? ?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容