在用寫directive的過程當中,咱們不免會用到&符號,而angular裏有幾個經常使用的通訊方式,以下:html
來看一個例子函數
指令代碼:spa
angular.module('directTest').directive('myInput', ['$timeout', function ($timeout) { return { restrict: 'E', scope: { placeholderText: '@placeholderText', iconStyle: '@iconStyle', buttonCallBack: '&buttonCallBack', keyCallBack: '&keyCallBack' }, templateUrl: window.tmplVersionPlus('views/my-input.client.view.html'), replace: true, link: function (scope) { //....dosomething } }; }])
html代碼:雙向綁定
<my-input icon-style="fa-search" placeholder-text="會員卡號/手機/二維碼" button-call-back="buttonSearch(phoneNum)" key-call-back="keySearch($event)"> </my-input>
模版代碼:rest
<form class="form-inline"> <input ng-keyup="keyCallBack($event)" placeholder="{{placeholderText}}" ng-model="searchParam" ng-model-options="{update:default}" type="text" class="form-control"> <span ng-click="buttonCallBack(searchParam)"> <i class="fa fa-plus" ng-class="iconStyle ? iconStyle : 'fa-plus' "></i> </span> </div> </form>
咱們想點擊icon的時候執行buttonCallBack這個函數,並將input的值,即searchParam傳回指令裏,看成參數,而後controller就能夠執行時就能夠拿到這個參數裏。 可是,這是不能夠的。 如前邊所示,通訊方式有三種,而傳參,是不能夠的。 解決方案:將參數看成雙向綁定的值=,而後controller就能夠拿到了。 html代碼修改:code
<my-input icon-style="fa-search" ng-model="phoneNum" placeholder-text="會員卡號/手機/二維碼" button-call-back="buttonSearch(phoneNum)" key-call-back="keySearch($event)"> </my-input>
指令代碼:修改scopeorm
scope: { searchParam: '=ngModel', placeholderText: '@placeholderText', iconStyle: '@iconStyle', buttonCallBack: '&buttonCallBack', keyCallBack: '&keyCallBack' },
模版代碼:htm
<span ng-click="buttonCallBack()"> //這裏不用傳參 <i class="fa fa-plus" ng-class="iconStyle ? iconStyle : 'fa-plus' "></i> </span>
彷佛還有一個$event,能省則省,直接在link裏作處理,不如不行仍是傳一下吧,能夠將searchParam修改成對象對象
link: function (scope) { //....dosomething scope.keySearch = function($event) { if ( $event.keyCode === 13 ) { if ( scope.keyCallBack ) { scope.keyCallBack(); } } }; }
傳參還有$emit()子到父 $broadcast父到子字符串