Reputation: 23
Could someone help me with this question. I am trying to understand how can I access the variable "new_name_input" inside one of my functions. The goal it's just to set my variable with the name choosen. I would be glad if someone could explain it to me or/and show me how can I make it.
See code below.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',['$scope',function($scope){
$scope.names=
[
{nome:'Renan'},
{nome:'Geraldo'}
];
$scope.newNames=
[
{nome:'Fernando'},
{nome:'José'}
];
$scope.transfer=function(novoNome,place){
alert(novoNome.nome);
this.place = novoNome.nome;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<div style='border:1px solid black;display:inline;margin:10px 10px 10px 10px'
ng-repeat='name in names'>
<input type='text' ng-model='new_name_input'/>
<div>
<p ng-click='transfer(new_name,new_name_input)' ng-repeat='new_name in newNames'>
{{new_name.nome}}
</p>
</div>
</div>
</body>
When I click on the names written, the names does not get added in the textbox. I am wondering how can I do it without remove the ng-repeat from the code
Upvotes: 2
Views: 552
Reputation: 30995
Not sure I'm following your question completely, but is this what you're attempting to do? Basically, you need a "." in the ng-model
in order to have two-way bindings work with primitives. I used ng-init
to create a new object to achieve that, but I wonder if you mean to get the new value back into the name
object? If so, you can drop the ng-init
and just pass the name
object into the transfer method instead.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',['$scope',function($scope){
$scope.names=
[
{nome:'Renan'},
{nome:'Geraldo'}
];
$scope.newNames=
[
{nome:'Fernando'},
{nome:'José'}
];
$scope.transfer=function(novoNome,nameVm){
alert(novoNome.nome);
nameVm.new_name_input= novoNome.nome;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<div style='border:1px solid black;display:inline;margin:10px 10px 10px 10px'
ng-repeat='name in names' ng-init="nameVm = {}">
<input type='text' ng-model='nameVm.new_name_input'/>
<div>
<p ng-click='transfer(new_name,nameVm)' ng-repeat='new_name in newNames'>
{{new_name.nome}}
</p>
</div>
</div>
</body>
Upvotes: 1