[英]$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.