two way binding on primitive variables in angularjs directive

别说谁变了你拦得住时间么 提交于 2020-01-04 04:37:09

问题


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>

how can this be achieved?


回答1:


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";

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>

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.

for additional information, angularjs actually has a documentation about it https://github.com/angular/angular.js/wiki/Understanding-Scopes




回答2:


I just realized that if your directive isn't inside an ng-if it will work with primitive bindings. Maybe the problem is that your bind is inside an ng-if. Try to use ng-show instead. Maybe it will work.

Passing the primitive this way:

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



来源:https://stackoverflow.com/questions/38078884/two-way-binding-on-primitive-variables-in-angularjs-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!