defaultcheckbox defaultcheckbox - 2 months ago 7
AngularJS Question

Set value on text input elements from dropdown

I have a dropdown that can be used to select an object. After making the selection, the application should use properties of that object to set the value on two input fields. I created the code below, but I am unable to set the value of the input fields. Can you advise?

Here is the view


<div class="row ui-section">
<div class="col-lg-8 clearfix">
<h2 class="section-header"></h2>
</div>
<div class="col-md-12">
<select ng-model="user" ng-change="getPhoneAndEmail(user)" >
<option ng-repeat="user in users" value="{{user}}">
{{user.name}}
</option>
</select>
{{name}}
{{user}}
<input ng-model="user.name">
<input ng-model="user.phone">
</div>
</div>
</main>


Here is the controller.

var App = angular.module("App",[]);
App.controller("cnt-asignaturas", ["$scope", "$http", function($scope,$http){

$scope.users = [
{
name:"Johnny",
"parentId":"1",
"email": "aa@aa.com",
"phone": "2125551212"
},{
name:"Kelvin",
"parentId":"2",
"email": "aa@aa.com",
"phone": "2125551212"
},{
name:"Jerry",
"parentId":"3",
"email": "aa@aa.com",
"phone": "2125551212"
}];

$scope.getPhoneAndEmail = function(user){

$scope.name = user.name;
$scope.phone = user.phone;

}

}]);

Answer

{{}} always return string so at the end you will not send javascript object to your controller method.

You could either use ng-options or you can send index and get it from array at your controller...

ng-options solution

<select ng-model="user" 
        ng-change="getPhoneAndEmail(user)" 
        ng-options="user as user.name for user in users">
</select>

index solution

<select ng-model="user" ng-change="getPhoneAndEmail(user)">
   <option ng-repeat="user in users" value="{{$index}}">
       {{user.name}}
   </option>
</select>

and controller

$scope.getPhoneAndEmail = function(index){
  var user = $scope.users[index];
  $scope.name = user.name;
  $scope.phone = user.phone;
}
Comments