Reputation: 411
I have 3 data. What I want now is to update them all using a one button but I don't know how to start or how can I get the id of each data. When the data is updated it should alert the updated value.
Any suggestions for this? Thanks
angular.module('myApp', [])
.controller('bookCtrl', function ($scope) {
$scope.book = {
name: 'Session Invites',
friends: [{
'id': 1,
'name': 'raju'
}, {
'id': 2,
'name': 'radha'
}, {
'id': 3,
'name': 'luttappi'
}]
};
$scope.update = function (friend) {
alert(friend.name);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="bookCtrl">
<div ng-repeat="friend in book.friends">
<input type="text" ng-model="friend.name" />
</div>
<input type="button" id="btn" name="btn" value="update" ng-click="update(friend)" />
</div>
</div>
Upvotes: 0
Views: 2626
Reputation: 10422
<div ng-controller="bookCtrl">
<div ng-repeat="friend in book.friends">
<input type="text" ng-model="friend.name" />
</div>
<input type="button" id="btn" name="btn" value="update" ng-click="update(friend)" />
</div>
You are passing friend
in the update
. But it is undefined I guess. Pass book.friends
and find updated results
<input type="button" id="btn" name="btn" value="update" ng-click="update(book.friends)" />
$scope.update = function(friends) {
for (var i = 0; i < friends.length; i++) {
var friendId = friends[i].id;
}
alert(friends);
};
Upvotes: 0
Reputation: 373
This is not pure angular way. But gets the job done.
You will need to iterate through the objects and set them all to a given name.
$scope.update =function(selectedfriend){ angular.forEach($scope.friends, function(friend, index) {
friend.name = selectedfriend.name
}); }
Upvotes: 0
Reputation: 1331
You can do something like this:
Doing a forEach
on book.friends
and send the book.friends
(being modify in the html)
angular.module('myApp', [])
.controller('bookCtrl', function ($scope) {
$scope.book = {
name: 'Session Invites',
friends: [{
'id': 1,
'name': 'raju'
}, {
'id': 2,
'name': 'radha'
}, {
'id': 3,
'name': 'luttappi'
}]
};
$scope.update = function (friends) {
$scope.book.friends.forEach(function(v, i){
v.name = friends[i].name;
});
console.log($scope.book.friends);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="bookCtrl">
<div ng-repeat="friend in book.friends">
<input type="text" ng-model="friend.name" />
</div>
<input type="button" id="btn" name="btn" value="update" ng-click="update(book.friends)" />
</div>
</div>
Upvotes: 1