angularjs 指令中原始变量的两种绑定方式 [英] two way binding on primitive variables in angularjs directive
问题描述
尝试在使用原始对象时对 AngularJS 指令进行 2 向绑定是行不通的,例如:
Trying to have 2 way binding on an AngularJS directive while using primitive objects is not working, for example:
<custom-directive ng-model="variable"></custom-directive>
如何实现?
推荐答案
为了在 javascript(不仅仅是 angularjs)中有 2 路绑定,我们必须传递一个对象(这是由 javascript 的评估策略引起的 - 可以阅读更多关于这里 https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing).基本上发生的事情是,当我们传递一个原始变量时,它是通过值传递并重新创建的,而不是通过引用传递.只有对象通过引用传递.
In order to have 2 way binding in javascript (not just angularjs), we have to pass an object (this is caused by javascript's evaluation strategy - can read more about it here https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing). basically what is happening is that when we pass a primitive variable, its been passed by value and re-created, instead of been passed by reference. only objects are passed by reference.
所以这个问题可以通过传递变量的父对象来解决,例如:
So this issue can be solved by passing the variable's parent object, for example:
<custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive>
然后,将指令中的对象修改如下:
and then, modifying in object in the directive as following:
parentObj[variable] = "whatever";
这样,我们将保持变量与 parentObj 之间的连接.
this way, we will keep the connection between the variable to the parentObj.
另一种选择是通过父对象传递模型,例如:
another option would be passing the model with the parent obj, for example:
<custom-directive ng-model="parentObj.variable"></custom-directive>
点是这个例子的重要组成部分.它实际上是 angular 的最佳实践,始终使用 parentObj-dot-property 传递变量.
the dot is an important part of this example. its actually a best practice by angular to always pass variables with the parentObj-dot-property.
有关其他信息,angularjs 实际上有关于它的文档 https://github.com/angular/angular.js/wiki/Understanding-Scopes
for additional information, angularjs actually has a documentation about it https://github.com/angular/angular.js/wiki/Understanding-Scopes
这篇关于angularjs 指令中原始变量的两种绑定方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!