[英]$scope and ng-model in the same directive
I have a directive that saves in a model in the Controller. 我有一个保存在Controller模型中的指令。 It is a "text-button" (as per requirements) which is just a read-only textbox.
它是一个“文本按钮”(根据要求),只是一个只读文本框。 There are three text-buttons per "Line" and 13 "Lines".
每个“行”和13个“行”有三个文本按钮。
I need to pull up a selection modal and load some data in depending on what was clicked, so that a new selection can be made. 我需要调出选择模式并根据单击的内容加载一些数据,以便可以进行新选择。
Although the model on the controller is changed, I don't know what was changed by the time the selection modal pops up. 尽管控制器上的模型已更改,但我不知道在弹出选择模式时发生了什么更改。
Model: 模型:
$scope.Lines = {
"eg1": { one: '', two: '', three: '' },
"eg2": { one: '', two: '', three: '' },
"eg3": { one: '', two: '', three: '' },
"eg4": { one: '', two: '', three: '' },
... 9 more ...
};
Directive: 指示:
.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" />'
};
});
View: 视图:
<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 ...
I've looked at $watch and $scope.watch, but nothing seems to be able to tell me what in a particular model has changed. 我看了看手表$ $和scope.watch,但似乎没有任何能告诉我在一个特定的模式发生了什么变化。
https://stackoverflow.com/a/15113029/1913371 https://stackoverflow.com/a/15113029/1913371
In the end, you need to isolate the scope of your directive so you have a chance to get to the ngModel
of each line: 最后,您需要隔离指令的范围,以便有机会进入每一行的
ngModel
:
scope: {
ngModel: '@',
popModal: '='
}
then you can use it in your callback: 然后可以在回调中使用它:
elm.on('click', function () {
$scope.popModal($scope.ngModel); //<--you get the ng-model here!
});
However, this means you also lose access to popModal()
which I guess is defined in the controller scope. 但是,这意味着您也将失去对
popModal()
访问权限,我猜这是在控制器作用域中定义的。 To fix this, you need to hand it in as a second parameter (I named it pop-modal
): 要解决此问题,您需要将其作为第二个参数(我将其命名为
pop-modal
):
<text-button ng-model="Lines.eg1.one" pop-modal="popModal"></text-button>
Tying it all together, here's a JSBin using Angular 1.2 (although you really should get away from that). 结合在一起, 这是一个使用Angular 1.2 的JSBin (尽管您确实应该摆脱这种情况)。
If you are using AngularJs 1.3+, you can use 'controllerAs' in the directive definition object. 如果您使用的是AngularJs 1.3+,则可以在指令定义对象中使用“ controllerAs”。 Then create a controller to do popModal.
然后创建一个控制器来执行popModal。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.