Ben*_*aki 3 angularjs angularjs-directive
尝试在使用原始对象时对AngularJS指令进行双向绑定不起作用,例如:
<custom-directive ng-model="variable"></custom-directive>
Run Code Online (Sandbox Code Playgroud)
怎么能实现呢?
为了在javascript(不仅仅是angularjs)中进行双向绑定,我们必须传递一个对象(这是由javascript的评估策略引起的 - 可以在这里阅读更多关于它的信息https://en.wikipedia.org/wiki/Evaluation_strategy# Call_by_sharing).基本上发生的事情是,当我们传递一个原始变量时,它已经被值传递并重新创建,而不是通过引用传递.只有对象通过引用传递.
所以这个问题可以通过传递变量的父对象来解决,例如:
<custom-directive ng-model-name="variable" ng-model-parent="parentObj"></custom-directive>
Run Code Online (Sandbox Code Playgroud)
然后,在指令中的对象中修改如下:
parentObj[variable] = "whatever";
Run Code Online (Sandbox Code Playgroud)
这样,我们将保持变量与parentObj之间的连接.
另一种选择是使用父obj传递模型,例如:
<custom-directive ng-model="parentObj.variable"></custom-directive>
Run Code Online (Sandbox Code Playgroud)
点是这个例子的重要部分.它实际上是angular的最佳实践,总是使用parentObj-dot-property传递变量.
有关其他信息,angularjs实际上有一个关于它的文档https://github.com/angular/angular.js/wiki/Understanding-Scopes
归档时间: |
|
查看次数: |
2680 次 |
最近记录: |