[英]Add directives from directive in AngularJS but keep ng-model binded
This question is linked to following question: 该问题与以下问题相关:
Add directives from directive in AngularJS 从AngularJS中的指令添加指令
In suggested answer, there's problem that ng-model is not updating because element is being compiled in directive. 在建议的答案中,存在ng-model不更新的问题,因为element是在指令中编译的。 What I expected is that, after I change select option, ng-model will be binded to selected item, but it's not.
我所期望的是,在更改选择选项后,ng-model将绑定到所选项目,但事实并非如此。 Is there any way to fix it?
有什么办法可以解决?
Plunker: http://plnkr.co/edit/Tw1Pbt?p=preview Plunker: http ://plnkr.co/edit/Tw1Pbt?p = preview
Specificly: Specificly:
<select ng-options="s for s in selects" ng-model="el" common-things>
<option value=""></option>
</select>
{{el}}
Here ng-model (el) has always same value, no matter what option I choos from select 无论我选择哪个选项,ng-model(el)始终具有相同的值
Same problem is if I have isolated scope inside directive, for instance: 同样的问题是,如果我在指令内部隔离了范围,例如:
<input type=text common-things ng-model="el.val" otherdata="something"/>
I eexpect, as I write something inside input, that {{el.val}} would have that value, but it's not being updated. 我预计,当我在输入中编写一些内容时,{{el.val}}会具有该值,但是不会被更新。
Your additional directive creates a new scope for the <select>
element. 您的附加指令为
<select>
元素创建了一个新作用域。 Due to JavaScript Prototype Inheritance , the property el
ends up on the directive's scope rather than the parent controller's scope. 由于JavaScript原型继承 ,属性
el
最终位于指令的作用域而不是父控制器的作用域。 This is a common pitfall, and a major reason to always use a dot in angular bindings . 这是一个常见的陷阱,也是在角度绑定中始终使用点的主要原因。
The quick fix for this is to define el
on the main controller as an object, and set a property of the object. 快速解决方案是在主控制器上将
el
定义为对象,并设置该对象的属性。
$scope.el = {};
$scope.el.val=2;
<select ng-options="s for s in selects" ng-model="el.val" common-things>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.