angularjs指令中基元变量的双向绑定

angularjs指令中基元变量的双向绑定,angularjs,angularjs-directive,Angularjs,Angularjs Directive,在使用基本体对象时尝试对AngularJS指令进行双向绑定无效,例如: <custom-directive ng-model="variable"></custom-directive> <custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive> <custom-directive ng-model="parentOb

在使用基本体对象时尝试对AngularJS指令进行双向绑定无效,例如:

<custom-directive ng-model="variable"></custom-directive>
<custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive>
<custom-directive ng-model="parentObj.variable"></custom-directive>


如何实现这一点?

为了在javascript中实现双向绑定(不仅仅是angularjs),我们必须传递一个对象(这是由javascript的评估策略引起的,可以在这里了解更多)。基本上,当我们传递一个原语变量时,它会被值传递并重新创建,而不是被引用传递。只有对象通过引用传递

因此,可以通过传递变量的父对象来解决此问题,例如:

<custom-directive ng-model="variable"></custom-directive>
<custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive>
<custom-directive ng-model="parentObj.variable"></custom-directive>
这样,我们将保持变量与parentObj之间的连接

另一个选项是将模型与父对象一起传递,例如:

<custom-directive ng-model="variable"></custom-directive>
<custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive>
<custom-directive ng-model="parentObj.variable"></custom-directive>

圆点是本示例的重要部分。实际上,angular的最佳实践是始终使用parentObj dot属性传递变量


关于其他信息,angularjs实际上有一个关于它的文档

我刚刚意识到,如果您的指令不在ng中,那么它将与原语绑定一起工作。可能问题是绑定在ng if中。尝试使用ng show代替。也许它会起作用

以这种方式传递原语:


好的做法是在定义controllerIt时使用的
点规则(通过定义对象)/
controllerAs
语法。我将我的ng if更改为ng show,并且我能够仅将标志(布尔值)作为基本数据类型传递,并且我能够在调用的部分中进行更改。