html input ng model,Angular自定义指令中传递ngModel
根據項目需要,希望寫一個自定義指令,將指令中傳遞的數據(比如:my-model="name"),綁定到template中的ng-model中,并且可以被外部作用域使用。
參考了《Angular權威指南》8.2節“向指令中傳遞數據”,看起來比較混亂,理解起來比較費力。同時也參考了其他博主的博文,但是依然未能達到預期目的。搗騰了大半天,終于搞定了。
解決方案
html:
js:
.directive("myInput", function() {
return {
restrict: 'E',
replace: true,
template: '
' +'{{myAddon}}' +
'' +
'' +
'
',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 中獲取和修改。
實現的效果為:點擊刪除按鈕,可以將input框中的數據清除。
總結:
唯一的修改就是將“@”綁定策略改成了“=”,然后將{{ }}移除。簡單吧,/淚流滿面……
可以參考博文:
歡迎評論指正,轉載請標明出處。
總結
以上是生活随笔為你收集整理的html input ng model,Angular自定义指令中传递ngModel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BBFT与FBFT/HotStuff的区
- 下一篇: html判断安装没安装qq,QQ6.1体