Reputation: 9517
I'm trying to programmatically bind a variable inside my Controller to a model bound to an input like this
<body ng-app="myApp">
<div ng-controller="MyController">
<input type="text" ng-model="myVar1" /> {{ myVar1 }}
<br />
<input type="text" ng-model="myVar2" /> {{ myVar2 }}
<br />
{{ myVar3 }}
</div>
</body>
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function($scope){
$scope.myVar3 = $scope.myVar1;
}]);
But as you can see in this fiddle the value of myVar3 does not change as I type inside the first input. I know that in any language primitive variables are copied by value and not by reference so could just define my models as objects and then copy the reference to myVar3 like this (see fiddle):
<body ng-app="myApp">
<div ng-controller="MyController">
<input type="text" ng-model="myVar1.value" /> {{ myVar1.value }}
<br />
<input type="text" ng-model="myVar2.value" /> {{ myVar2.value }}
<br />
{{ myVar3.value }}
</div>
</body>
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function($scope){
$scope.myVar1 = {};
$scope.myVar2 = {};
$scope.myVar3 = $scope.myVar1;
}]);
The problem is that I don't want to create objects everytime I need to dinamically link a variable to a model, it's there a more "angular" way to achieve the same result using the first code?
Thanks,
Upvotes: 2
Views: 107
Reputation: 2225
The line The line $scope.myVar3 = $scope.myVar1;
will only execute one time, when the controller is loaded in the page. What you need is to place that sentence in a controller function bound to any of the input's key events.
Fiddle: http://jsfiddle.net/dGvm8/
Upvotes: 1