Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 35126  / 11 Years ago, fri, april 12, 2013, 12:00:00

I'm trying to bind the value of an input field to a variable.
I don't know the name of this variable a priori; it is stored in another variable.



This is the html:



<body ng-controller=stageController>
<form name=myForm novalidate=>
<input type=text name=myText ng-model=model />
</form>
</body>


and this is the controller:



function stageController($scope) {
$scope.model = 'realModel'; // contains the name of the variable that i would bind to the field
$scope.realModel = 'initial value of the field';
}


I made also a fiddle.



This doesn't work because currently the binding is between the input field and the model variable. Instead I would bind the input field to the variable which name is stored inside the $scope.model variable (in this case realModel).



Is it possible? How?


More From » angularjs

 Answers
12

Yes, its possible. I dont understand why you'd want to do it, but I can show you how to. I couldnt start the fiddle, but I copied to a plnkr: http://plnkr.co/edit/o1gFf1lMq4Pg5iVoVyUN?p=preview



You create a directive that transform the original template into a new one using $compile. The new directive:



directive('ngBindModel',function($compile){
return{
compile:function(tEl,tAtr){
tEl[0].removeAttribute('ng-bind-model')
return function(scope){
tEl[0].setAttribute('ng-model',scope.$eval(tAtr.ngBindModel))
$compile(tEl[0])(scope)
console.info('new compiled element:',tEl[0])
}
}
}
})


Updated html (change from ng-model to ng-bind-model, the new directive)



<input type=text name=myText ng-bind-model=model  />

[#78958] Wednesday, April 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;