[英]$scope and ng-model in the same directive
我有一個保存在Controller模型中的指令。 它是一個“文本按鈕”(根據要求),只是一個只讀文本框。 每個“行”和13個“行”有三個文本按鈕。
我需要調出選擇模式並根據單擊的內容加載一些數據,以便可以進行新選擇。
盡管控制器上的模型已更改,但我不知道在彈出選擇模式時發生了什么更改。
模型:
$scope.Lines = {
"eg1": { one: '', two: '', three: '' },
"eg2": { one: '', two: '', three: '' },
"eg3": { one: '', two: '', three: '' },
"eg4": { one: '', two: '', three: '' },
... 9 more ...
};
指示:
.directive('textButton', function () {
return {
restrict: 'E',
require: 'ngModel',
link: function ($scope, elm, attrs, ctrl) {
elm.on('click', function () {
$scope.popModal(this); //<--I want the ng-model here!
});
},
template: '<input type="text" readonly="readonly" class="form-control" />'
};
});
視圖:
<ul>
<li> <text-button ng-model="Lines.eg1.one"></text-button> </li>
<li> <text-button ng-model="Lines.eg1.two"></text-button> </li>
<li> <text-button ng-model="Lines.eg1.three"></text-button> </li>
<ul>
<ul>
<li> <text-button ng-model="Lines.eg2.one"></text-button> </li>
<li> <text-button ng-model="Lines.eg2.two"></text-button> </li>
<li> <text-button ng-model="Lines.eg2.three"></text-button> </li>
<ul>
... 11 more ...
我看了看手表$ $和scope.watch,但似乎沒有任何能告訴我在一個特定的模式發生了什么變化。
最后,您需要隔離指令的范圍,以便有機會進入每一行的ngModel
:
scope: {
ngModel: '@',
popModal: '='
}
然后可以在回調中使用它:
elm.on('click', function () {
$scope.popModal($scope.ngModel); //<--you get the ng-model here!
});
但是,這意味着您也將失去對popModal()
訪問權限,我猜這是在控制器作用域中定義的。 要解決此問題,您需要將其作為第二個參數(我將其命名為pop-modal
):
<text-button ng-model="Lines.eg1.one" pop-modal="popModal"></text-button>
如果您使用的是AngularJs 1.3+,則可以在指令定義對象中使用“ controllerAs”。 然后創建一個控制器來執行popModal。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.