i'm learning angularjs , hoping can problem i'm facing.
i have array of objects(friends) in controller i've bound select element using ngoptions. using dropdown, user can select friend , view friends information (id, name, age, etc).
i have included button allows user change age of selected friend. when button clicked, friends age changed , reflected in ui. however, age change not reflected in array if user selects different friend drop down , selects original friend, age shown original age before change.
hopefully plunker can clarify explanation: http://plnkr.co/edit/9yfkst75bhqdimzjdlvi?p=preview
angular.module('defaultvalueselect', []) .controller('examplecontroller', ['$scope', function($scope) { $scope.friends = [{id:5, name: "jack", age: 35}, {id:8, name: "jill", age: 38}]; $scope.newage; $scope.savenewage = function(){ $scope.selectedfriend.age = $scope.newage; } }]); <!doctype html> <html ng-app="defaultvalueselect" > <head> <meta charset="utf-8"> <title>angularjs plunker</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js"></script> <script src="app.js"></script> </head> <body ng-controller="examplecontroller"> <form name="myform"> <label for="myselect">choose friend:</label> <select name="myselect" id="myselect" ng-options="friend.name friend in friends track friend.id" ng-model="selectedfriend"></select> </form> <hr> <tt>selected friend = {{selectedfriend}}</tt><br/> <input type="text" class="form-control" ng-model="newage"> <button ng-click="savenewage()">update age</button> </body> </html>
my background in c++ , c#. in languages, problem due copying object array , changing rather changing reference object in array. i've been searching internet, , seems problem may have scope i'm in, i'm not sure.
if add loop savenewage function match selected person person in array (i used id match) , set age there should want.
$scope.savenewage = function() { $scope.selectedfriend.age = $scope.newage; (var = 0; < $scope.friends.length; i++) { if ($scope.friends[i].id === $scope.selectedfriend.id) $scope.friends[i].age = $scope.selectedfriend.age; } }
as mentioned in ngoptions documentation
note: default, ngmodel watches model reference, not value. important when binding input directive model object or collection.
Comments
Post a Comment