【发布时间】:2014-07-17 15:46:42
【问题描述】:
我使用ng-model 的双向数据绑定不起作用。
父指令模板:
<div class="form-group">
<label>Company Phone</label>
<input ng-model="formData.company_phone" type="phonenumber" class="form-control" placeholder="Company Phone">
</div>
还有子指令:
.directive('input', [function(){
return: {
restrict: 'E',
require: '?ngModel',//right now this is binding to this directive scope, not a parent one
link: function($scope, element, attr, ngModel){
if (attr.type !== 'phonenumber') {
return;
}
//some code to validate a phone number
$scope.$apply(function () {
//bind updated number, but I need this to reflect in the parent scope
$scope[attr.ngModel] = formattedNumber;
}
【问题讨论】:
-
一些相关代码会有所帮助
-
@charlietfl 我添加了一些代码,抱歉。
-
如果你使用 ng-model,并且绑定到同一个模型,那么它们已经是双向绑定到各自的视图。它应该可以工作 OOTB。如果它不起作用,请尝试找出 ng-models 是否引用相同的实例。有几篇关于为什么 ng-model 应该有一个“。”的帖子。在里面 - 它可能在这里相关。
-
@pixelbits 我正在使用 ng-model 和模型的对象表示法,实际上我只是弄清楚我做错了什么。我会发布一个带有解释的答案。
标签: angularjs angularjs-directive angularjs-scope