$scope和 ng 模型在同一指令中
$scope and ng-model in the same directive
我有一个指令,它保存在控制器的模型中。它是一个"文本按钮"(根据要求),只是一个只读文本框。每个"行"和 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 ...
我看过$watch和$scope.watch,但似乎没有什么能告诉我特定模型中发生了哪些变化。
https://stackoverflow.com/a/15113029/1913371
最后,您需要隔离指令的范围,以便有机会了解每行的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>
将它们结合在一起,这里有一个使用 Angular 1.2 的 JSBin(尽管你真的应该摆脱它)。
如果您使用的是 AngularJs 1.3+,则可以在指令定义对象中使用 'controllerAs'。然后创建一个控制器来做popModal。
相关文章:
- 自定义指令中的AngularJS ng模型
- 显示/隐藏有关模型更改的指令内容
- 为什么我的指令(使用链接)没有出现,并允许ng模型看到它
- NG-重复中断指令模型绑定
- 为什么ng选项指令需要ng模型
- 需要使用触摸屏从 AngularJS 指令中更新模型
- 角度指令:当选择更改时,ng 模型未正确更新
- 角度指令没有更新模型视图
- 角度 2 使用指令防止输入和模型更改
- 将ng模型转发到指令中的元素的正确方法是什么
- 无法更新指令的模型
- 如何在事件上对jquery上的ng模型进行指令更新
- 将 ng 模型值传递给角度指令
- 输入文本的ng重复没有填充指令中的ng模型
- mocking和测试指令,隔离范围包含ng模型
- 将用户键入的模型更改为自定义的Angular指令
- 在控制器中将 ng 模型值返回为空的指令
- 角度 - 基于模型创建指令
- 如何将指令模型绑定到异步服务数据
- AngularJS指令模型符号与TypeScript接口