根據項目需要,希望寫一個自定義指令,將指令中傳遞的數據(比如:my-model="name"),綁定到template中的ng-model中,并且可以被外部作用域使用。

參考了《Angular權威指南》8.2節(jié)“向指令中傳遞數據”,看起來比較混亂,理解起來比較費力。同時也參考了其他博主的博文,但是依然未能達到預期目的。搗騰了大半天,終于搞定了。
解決方案
html:
<div my-input my-addon="test1" my-model="user.test1" my-placeholder="it's test1"></div>
<div my-input my-addon="test2" my-model="user.test2" my-placeholder="it's test2" my-maxlength="11"></div>
js:
.directive("myInput", function() {
return {
restrict: 'E',
replace: true,
template: '<div class="input-group">' +
'<span class="input-group-addon">{{myAddon}}</span>' +
'<input class="form-control" type="text" ng-model="myModel" ng-change="myInput.watch()" placeholder="{{myPlaceholder}}" maxlength="{{myMaxlength}}">' +
'<span class="input-group-addon"><\img src="/images/user/icon_delete.png" ng-click="myInput.delete()" class="icon-delete" width="16px" height="16px"></span>' +
'</div>',
scope: {
myAddon: '@',
myModel: '=', // 重點:如果需要跟外部作用域通信,需要改成“=”,template中的myModel不可用{{ }}
myPlaceholder: '@',
myMaxlength: '@'
},
controller: function($scope, $element) {
$scope.myInput = {
"watch": function() {
var val = $element.find("input").val();
console.log($element.find("input").val());
$scope.myModel = val;
console.log($scope.myAddon)
},
"delete": function() {
$scope.myModel = '';
$element.find("input").val('');
}
}
}
}
})

效果圖

Chrome Element
$scope.user.test1、$scope.user.test2 直接可以在 controller 中獲取和修改。
實現(xiàn)的效果為:點擊刪除按鈕,可以將input框中的數據清除。
總結:
唯一的修改就是將“@”綁定策略改成了“=”,然后將{{ }}移除。簡單吧,/淚流滿面……
可以參考博文:
歡迎評論指正,轉載請標明出處。