I am a beginner in AngularJS.
I developped a Service with JAVA and I Consume it in angular to delete a Contact object.
In AngularJS I have this code on my home page :
<!--RESULTS-->
<form>
<table class="table table-striped" ng-controller="HomeController">
<tr>
<th></th>
<th>Nom</th>
<th>Prénom</th>
<th>Téléphone</th>
<th>Email </th>
<th></th>
</tr>
<tr ng-repeat="contact in allContacts | filter:search | orderBy:'lastName'">
<td align="center"><img src="{{contact.picture}}" height="40" width="40"/></td>
<td class="td_data">{{contact.lastName}}</td>
<td class="td_data">{{contact.firstName}}</td>
<td class="td_data">{{contact.phone_1+" "+contact.phone_2}}</td>
<td class="td_data">{{contact.email}}</td>
<td class="td_data"><button type="button" class="btn btn-danger" ng-controller="HomeController" ng-click="deleteContact(contact)"><i class="glyphicon glyphicon-trash"></i></button></td>
</tr>
</table>
In my controller I have this code :
var module = angular.module('home.controllers', [])
.run(function($rootScope) {
$rootScope.is_hide_add_message = true;
$rootScope.alert_message = "";
})
module.controller('HomeController', function ($scope, $rootScope, $state, Contacts, $timeout) {
var allContacts = {};
/** DELETE A CONTACTS*/
$scope.deleteContact = function(contact){
/** GET INDEX OF OBJECT TO DELETE */
var index = $scope.allContacts.indexOf(contact);
/** DELETE THE OBJECT SELECTED */
Contacts.deleteContact(contact.id);
/** DELETE THE OBJECT FROM THE JSON */
$scope.allContacts.splice(index, 1);
$rootScope.alert_message = "Le contact a été supprimé avec succès.";
/**DISPLAY THE MESSAGE*/
$rootScope.is_hide_add_message = false;
$timeout(function() {
$rootScope.is_hide_add_message = true;
}, 3000);
};
}
);
when I click on the delete button the object is deleted in the database but my <table> is not refreshed. When I debug the code $scope.allContacts.splice(index, 1); is working fine. but the table is not refreshed
I think the problem lays with the fact you specify ng-controller="HomeController" twice. You can delete it on the button
May be this will help i have added demo code here.
please have a look on it
var app = angular.module('myApp', []);
app.controller('HomeController', function($scope) {
var Contacts = [{
"lastName": "ABC1",
"firstName": "XYZ",
"phone_1": "123456",
"phone_2": "789456",
"email": "abcXyz#gmail.com",
}, {
"lastName": "ABC2",
"firstName": "XYZ",
"phone_1": "123456",
"phone_2": "789456",
"email": "abcXyz#gmail.com",
}, {
"lastName": "ABC3",
"firstName": "XYZ",
"phone_1": "123456",
"phone_2": "789456",
"email": "abcXyz#gmail.com",
}, {
"lastName": "ABC4",
"firstName": "XYZ",
"phone_1": "123456",
"phone_2": "789456",
"email": "abcXyz#gmail.com",
}, {
"lastName": "ABC5",
"firstName": "XYZ",
"phone_1": "123456",
"phone_2": "789456",
"email": "abcXyz#gmail.com",
}];
$scope.allContacts = Contacts;
/** DELETE A CONTACTS*/
$scope.deleteContact = function(contact) {
/** GET INDEX OF OBJECT TO DELETE */
var index = $scope.allContacts.indexOf(contact);
/** DELETE THE OBJECT FROM THE JSON */
$scope.allContacts.splice(index, 1);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp">
<table class="table table-striped" ng-controller="HomeController">
<tr>
<th>Nom</th>
<th>Prénom</th>
<th>Téléphone</th>
<th>Email</th>
<th>Action</th>
</tr>
{{allContacts}}
<tr ng-repeat="contact in allContacts | filter:search | orderBy:'lastName'">
<td class="td_data">{{contact.lastName}}</td>
<td class="td_data">{{contact.firstName}}</td>
<td class="td_data">{{contact.phone_1+" "+contact.phone_2}}</td>
<td class="td_data">{{contact.email}}</td>
<td class="td_data">
<button type="button" class="btn btn-danger" ng-click="deleteContact(contact)">delete<i class="glyphicon glyphicon-trash"></i>
</button>
</td>
</tr>
</table>
Related
I just began learning AngularJS, and I am trying to create a pretty simple web application. Right now, I have some users. Each user is displayed in an individual table and each user has its own details which is displayed in a table under it.
$scope.userList = [{username: "Bob_t", detailsId: 1}, {username: "Mike_V", detailsId: 2}];
$scope.userDetails = [{Name: "Bob", Age: 20, id: "1"}, {Name: "Michael", Age: 18, id: "2"}];
You can see that each user has a reference to it's corresponding details (detailsId in userList corresponds to id in userDetails).
Basically, what I'm trying to do is initially have the details table hidden for each user. And when someone clicks the expand button for a specific user, open that user's corresponding details table and populate it with that user's details. What I'm having trouble with is getting the detailsId from the clicked expand button and then using that to query my DB to get the correct user's details to display in the table under it.
<div ng-repeat="user in userList | filter:searchBox">
<div class="uk-panel-box-secondary uk-overflow-container tableDiv uk-margin-large-bottom">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Username</th>
</tr>
</thead>
</table>
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="isOpened=!isOpened; showOrHideDetails(isOpened, param)" ng-class="{'uk-icon-plus-square-o': !isOpened, 'uk-icon-minus-square-o': isOpened}"></a>
</div>
<div class="uk-panel-box-secondary uk-overflow-container uk-margin-top uk-margin-large-left uk-margin-bottom tableDiv">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="details in userDetails" id={{user.id}}>
<td>{{details.Name}}</td>
<td>{{details.Age}}</td>
<td>
</td>
</tr>
</table>
</div>
</div>
my controller:
$http({
method : "GET",
url : "http://database:8081/userAccounts/"
}).then(function mySucces(response) {
$scope.userList = response.data;
}, function myError(response) {
// $scope.userList = response.statusText;
});
$scope.showOrHideDetails = function(isOpened, param)
if(isOpened){
console.log($scope.id)
$scope[id] = true;
console.log($scope.id);
$http({
method : "GET",
url : "http://database:8081/details?id=" + index
}).then(function mySucces(response) {
$scope.userDetails = response.data;
}, function myError(response) {
$scope.userDetails = response.statusText;
});
}
else{
$scope.showDetails = false;
}
}
What is really confusing to me is once I get the correct userDetails object after querying the DB, how do I populate the corresponding table with that info?
I know I probably need a model, but this confuses me because the number of users is unknown.
First, your code is a bit confuse..
After each query you're attributing the response (which one is the details of a single user) to the whole array userDetails:
$scope.userDetails = response.data;
While it should be:
$scope.userDetails.push(response.data);
In addition, you have a single variable called isOpened, for sure it won't work, because you have multiple buttons for only 1 variable.
So my suggestion is to change it to:
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="showOrHideDetails(user)" ng-class="{'uk-icon-plus-square-o': !user.isOpened, 'uk-icon-minus-square-o': user.isOpened}"></a>
Also you have to check if the userDetail is already in your userDetails array.
Finally, since you want to show the details based on the user, you can use the native filter, because you already have the id property of users in both arrays, as below:
<tr ng-if="user.isOpened" ng-repeat="details in userDetails | filter: { id: user.detailsId }" id={{user.id}}>
A simple demo:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$http'];
function MainCtrl($scope, $http) {
$scope.userList = [{
username: "Bob_t",
detailsId: 1
}, {
username: "Mike_V",
detailsId: 2
}];
$scope.userDetails = [{
Name: "Bob",
Age: 20,
id: "1"
}, {
Name: "Michael",
Age: 18,
id: "2"
}];
$scope.showOrHideDetails = function(user) {
user.isOpened = !user.isOpened;
function mySuccess(response) {
$scope.userDetails.push(response.data);
}
function myError(response) {
console.log(response.statusText);
}
if (user.isOpened) {
$http.get('http://database:8081/details?id=' + user.id)
.then(mySuccess)
.catch(myError);
} else {
$scope.showDetails = false;
}
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.4/js/uikit.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.4/css/uikit.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="user in userList | filter:searchBox">
<div class="uk-panel-box-secondary uk-overflow-container tableDiv uk-margin-large-bottom">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td ng-bind="user.username"></td>
</tr>
</tbody>
</table>
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="showOrHideDetails(user)" ng-class="{'uk-icon-plus-square-o': !user.isOpened, 'uk-icon-minus-square-o': user.isOpened}"></a>
</div>
<div class="uk-panel-box-secondary uk-overflow-container uk-margin-top uk-margin-large-left uk-margin-bottom tableDiv">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tr ng-if="user.isOpened" ng-repeat="details in userDetails | filter: { id: user.detailsId }" id={{user.id}}>
<td ng-bind="details.Name"></td>
<td ng-bind="details.Age"></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
I hope it helps!!
have you tried passing user from
<div ng-repeat="user in userList | filter:searchBox">
to function showOrHideDetails(user)
I have a static array and I am trying to show a particular field of this array through ng-repeat, but my array shows every time the ID field on single index.
This is what my output screenshot looks like
You can find my code below,
function monthCalendarController($scope, $http, $rootScope, $filter, $location, WebService, CalendarEventService) {
$scope.eventSelected = function(event) {
var params = {
id: event.event.id
};
var url = $rootScope.url + '/v1/show_event';
var token = window.localStorage['token'];
var result = WebService.makeServiceCallHeader(url, params, $rootScope.POST, token);
result.then(function(response) {
if (response.status == 200) {
CalendarEventService.addEvent(response.data.event);
$location.path("/calendarEvent");
} else {
WebService.showAlert('Problem in Loading');
}
}, function(response) {
console.log('' + JSON.stringify(response));
});
};
$scope.persons = [
{ "id": 1, "name": "A", "select": true },
{ "id": 2, "name": "B", "select": true },
{ "id": 3, "name": "C", "select": true },
{ "id": 4, "name": "D", "select": true },
{ "id": 5, "name": "E", "select": true },
{ "id": 6, "name": "F", "select": true },
{ "id": 0, "name": "G", "select": true }
];
console.log($scope.counts);
$scope.selectDate = function(date) {
$scope.selectedDate = date.date;
$scope.showEventsDiv = true;
};
};
HTML
<div ng-controller="monthCalendarController">
<table class="table table-bordered monthview-datetable monthview-datetable">
<thead>
<tr>
<th ng-show="showWeeks" class="calendar-week-column text-center">#
</th>
<th ng-repeat="label in labels track by $index" class="text-center">
<small>{{label}}
</small>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows track by $index">
<td ng-show="showWeeks" class="calendar-week-column text-center">
<small>
<em>{{ weekNumbers[$index] }}</em>
</small>
</td>
<td ng-repeat="dt in row track by dt.date"
class="monthview-dateCell"
ng-click="select(dt.date)"
ng-class="{\'text-center\':true, \'monthview-current\': dt.current&&!dt.selected&&!dt.hasEvent,\'monthview-secondary-with-event\': dt.secondary&&dt.hasEvent, \'monthview-primary-with-event\':!dt.secondary&&dt.hasEvent&&!dt.selected, \'monthview-selected\': dt.selected}">
<div ng-class="{\'text-muted\':dt.secondary}" ng-click="selectDate(dt.date)">
<p ng-repeat="person in persons">
{{person.id}}!
</p>
{{dt.label}}
</div>
</td>
</tr>
</tbody>
</table>
<div ng-if="showEventDetail" class="event-detail-container" ng-show="showEventsDiv">
<div class="scrollable" style="height: 200px">
<div class="col-md-12 col-xs-12" style="font-size: 18px; padding-left: 15px;">
<i class="ion-calendar">
</i>{{selectedDate.date |date:\'MM/dd/yyyy\'}}
</div>
<div style="clear: both">
</div>
<div class="item item-divider event">
Events
</div>
<table class="table table-bordered table-striped table-fixed">
<tr ng-repeat="event in selectedDate.events" ng-if="selectedDate.events">
<td ng-if="!event.allDay" class="monthview-eventdetail-timecolumn cal-date-txt">
{{event.startTime|date: \'HH:mm\'}} {{event.endTime|date: \'HH:mm\'}}
</td>
<td ng-if="event.allDay" class="monthview-eventdetail-timecolumn">
All day
</td>
<td class="event-detail cal-date-txt day" ng-click="eventSelected({event:event})">
{{event.title}}
</td>
</tr>
<tr ng-if="!selectedDate.events">
<td class="no-event-label">No Events</td>
</tr>
</table>
</div>
</div>
</div>
Array always shows ID single index.
Can someone explain and help me ? I can still not figure out why.
I have a list of dictionaries, and I want to toggle show all the students and their details for each classroom.
This is the HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="classrooms-details" ng-show="Students">
<table class="table table-striped">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Gender</th>
<th>Birthday</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.student.first_name}}</a></td>
<td>{{classroom.student.last_name}}</td>
<td>{{classroom.student.gender}}</td>
<td>{{classroom.student.birthday}}</td>
</tr>
</tbody>
</table>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Classroom</th>
<th>School</th>
<th>Academic year</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school.school_name}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
</tbody>
</table>
</div>
I've tried to use ng-click/ng-show, but it's not working.
And this is the script:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.classrooms = [{
"school": {
"id": 1,
"school_name": "IPSIA F. Lampertico",
"address": "Viale Giangiorgio Trissino, 30",
"city": "Vicenza"
},
"academic_year": "2015/2016",
"classroom": "1^A",
"floor": 0,
"students": [{
"classroom": 1,
"first_name": "Stefano",
"last_name": "Rossi",
"gender": "M",
"birthday": "1998-06-22"
}, {
"classroom": 1,
"first_name": "Luca",
"last_name": "Possanzini",
"gender": "M",
"birthday": "1999-11-22"
}]
}, {
"school": {
"id": 2,
"school_name": "ITIS A. Rossi",
"address": "Via Legione Gallieno, 52",
"city": "Vicenza"
},
"academic_year": "2015/2016",
"classroom": "2^B",
"floor": 0,
"students": [{
"classroom": 2,
"first_name": "Sergio",
"last_name": "Lazzari",
"gender": "M",
"birthday": "2001-01-29"
}]
}];
console.log($scope.classrooms);
});
I don't know how to access "students" values, and I'd like the students details to be shown only when clicking on the classroom name.
How could I accomplish this?
You just need to set a specific classroom as the "active" classroom and display the students within. The easiest way to do this would be something like:
View
<tr ng-if="activeClassroom" ng-repeat="student in activeClassroom.students">
<td>{{student.first_name}}</a></td>
<td>{{student.last_name}}</td>
<td>{{student.gender}}</td>
<td>{{student.birthday}}</td>
</tr>
...
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school.school_name}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
Controller
$scope.activeClassroom = null;
$scope.setActiveClassroom = function (classroom) {
$scope.activeClassroom = classroom;
};
I have an Angular SPA that features a cart (array) that users can add items to. I'd like to prevent the user from adding any particular item to the cart twice.
function CartForm($scope) {
$scope.products = [{
"description": "BB-8 Droid",
"qty": "1",
"cost": "99"
}, {
"description": "C-3PO Droid",
"qty": "1",
"cost": "499"
}, {
"description": "R2-D2 Astromech Droid",
"qty": "1",
"cost": "899"
}, {
"description": "R5-D4 Astromech Droid",
"qty": "1",
"cost": "899"
}, {
"description": "IG-88 Bounty Hunter Droid",
"qty": "1",
"cost": "899"
}];
$scope.invoice = {
items: []
};
$scope.addItem = function(product) {
$scope.invoice.items.push(product);
},
$scope.removeItem = function(index) {
$scope.invoice.items.splice(index, 1);
},
$scope.total = function() {
var total = 0;
angular.forEach($scope.invoice.items, function(item) {
total += item.qty * item.cost;
})
return total;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h2>Shopping Cart Example</h2>
<div ng:controller="CartForm">
<table class="table">
<thead>
<th>Description</th>
<th>Qty</th>
<th colspan="2">Price</th>
</thead>
<tr ng-repeat="product in products">
<td>{{product.description}}</td>
<td>{{product.qty}}</td>
<td>{{product.cost | currency }}</td>
<td>
<button class="btn btn-danger" ng-click="addItem(product)">ADD TO CART</button>
</tr>
</table>
<table class="table">
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
<tr ng:repeat="item in invoice.items">
<td>
<input type="text" ng:model="item.description" class="input-small">
</td>
<td>
<input type="number" ng:model="item.qty" ng:required class="input-mini">
</td>
<td>
<input type="number" ng:model="item.cost" ng:required class="input-mini">
</td>
<td>{{item.qty * item.cost | currency}}</td>
<td>
[<a href ng:click="removeItem($index)">X</a>]
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Total:</td>
<td>{{total() | currency}}</td>
</tr>
</table>
</div>
See working JSFiddle here: http://jsfiddle.net/tedleeatlanta/22591h2y/15/
You can add some logic to your AddItem to deal with all of this.
This isn't the most elegant way, but will get you going in the right direction - Something like this works well:
$scope.addItem = function(product) {
var exist = false;
for(var i = 0; i < $scope.invoice.items.length;i++){
if ($scope.invoice.items[i].description==product.description)
{
// having to use parseInt here because your Qty isn't a number...naughty naughty
$scope.invoice.items[i].qty = parseInt($scope.invoice.items[i].qty)+1;
exist = true;
}
}
if (!exist)
$scope.invoice.items.push(product);
},
It increases the Qty if it already exists, or adds it if it doesn't
See it running here http://jsfiddle.net/22591h2y/16/
Or, for something that doesn't need to parseInt - change your objects qty to ints, rather than strings.
See this update http://jsfiddle.net/22591h2y/17/
I have this Controller:
JApp.controller('WebsiteController', function($scope, $resource) {
var UsersService = $resource('/auth/users', {});
$scope.adding = false;
$scope.users = [];
$scope.addUser = function() {
$scope.adding = true;
UsersService.query({}, function(data) {
$scope.users = data;
$scope.selectedUser = data[0];
});
}
$scope.cancelAddUser = function() {
$scope.adding = false;
}
});
My HTML:
<section class="vbox" ng-controller="WebsiteController">
<section class="panel animated fadeInDown">
<header class="panel-heading">
<h3>{{selectedUser.last_name}} </h3> <!-- Just to test I print it here -->
</header>
<div class="panel-body m-b">
<div class="row text-sm wrapper">
#if (role_admin())
<i class="icon-plus"></i> New Website
#endif
</div>
<div class="table-responsive">
<table class="table table-striped b-t text-sm">
<thead>
<tr>
<th>URL</th>
<th>Assigned to</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- Outside this <tr> doesn't work -->
<tr ng-repeat="website in websites">
<td> {{website.url}}</td>
<td>
<span ng-repeat="assigned in website.users"> <span class="label label-info"> {{assigned.first_name}} </span> </span>
<a ng-click="addUser()" ng-hide="adding" class="btn btn-success btn-xs"> Add new </a></span>
<select ng-hide="!adding"
name="myselect"
ng-model="selectedUser"
ng-options="u.first_name for u in users">
</select>
Cancel
<input type="text" ng-model="selectedUser.first_name"> <!-- It works here! -->
</td>
<td>
<i class="icon-pencil"></i> Edit
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</section>
Updated: Notice that it works in my <input> next to the <select>, but doesn't work in my <header> (only binds once)
So when I click on the add user, the AJAX call will retrieve list of users, and successfully show it in the <select> and by default, selectedUser will be pointing at data[0] which is the first user. But now the two way binding is now bound to data[0] instead. If I change my selection to other user, selectedUser is not updated. But if I update my selectedUser, let's say the name, the name in the dropdown list also change.
I have tried not using the line
$scope.selectedUser = data[0];
but still doesn't work anyway, it is not bound at all though I specify ng-model="selectedUser".
The JSON returned:
[
{
"id": 1,
"role_id": 1,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "admin#admin.com",
"username": "admin",
"first_name": "Admin",
"last_name": "Istrator"
},
{
"id": 2,
"role_id": 2,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "johndoe#gmail.com",
"username": "john",
"first_name": "John",
"last_name": "Doe"
}
]
Anyone can help me with this? I am trying not to go down the $digest or $apply road if I don't have to.
UPDATE 2
The source of the problem is if I try to print out selectedUser outside of the following ng-repeat in my above HTML:
<tr ng-repeat="website in websites"> ...... </tr>
Fiddle to illustrate my problem: http://jsfiddle.net/jofrysutanto/4nfyV/3/
Try This
HTML:
<div ng-app="myApp">
<section class="vbox" ng-controller="WebsiteController">
<section class="panel animated fadeInDown">
<header class="panel-heading">
<h3>{{mySelectedUser.last_name}} </small> <!-- Just to test I print it here -->
</header>
<div class="panel-body m-b">
<div class="table-responsive">
<table class="table table-striped b-t text-sm">
<thead>
<tr>
<th>URL</th>
<th>Assigned to</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="website in websites">
<td>
<span ng-repeat="assigned in website.users"> <span class="label label-info"> {{assigned.first_name}} </span> </span>
<a ng-click="addUser()" ng-hide="adding" class="btn btn-success btn-xs"> Add new </a></span>
<select ng-hide="!adding"
name="myselect"
ng-model="selectedUser"
ng-change="abc(selectedUser)"
ng-options="u.first_name for u in users">
</select>
Cancel
<input type="text" ng-model="selectedUser.first_name"> <!-- It works here! -->
</td>
<td>
<i class="icon-pencil"></i> Edit
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</section>
</div>
Controller :
var JApp = angular.module('myApp', []);
JApp.controller('WebsiteController', function($scope) {
//var UsersService = $resource('/auth/users', {});
$scope.adding = false;
$scope.users = [];
$scope.websites = [
{
"id": 1,
"url": "www.google.com",
"cms": "Wordpress"
}
];
$scope.addUser = function() {
$scope.adding = true;
var data = [
{
"id": 1,
"role_id": 1,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "admin#admin.com",
"username": "admin",
"first_name": "Admin",
"last_name": "Istrator"
},
{
"id": 2,
"role_id": 2,
"created_at": "2013-09-19 05:54:36",
"updated_at": "2013-09-19 05:54:36",
"email": "johndoe#gmail.com",
"username": "john",
"first_name": "John",
"last_name": "Doe"
}
];
// UsersService.query({}, function(data) {
$scope.users = data; // suppose data is coming from UsersService.query
$scope.selectedUser = data[1];
$scope.mySelectedUser = $scope.selectedUser ;
// });
}
$scope.abc = function(a) {
$scope.mySelectedUser = a;
}
$scope.cancelAddUser = function() {
$scope.adding = false;
}
});
See DEMO
The value of the select dropdown options is u.first_name, so either do this:
$scope.selectedUser = data[0].first_name;
Or change it to use ids or something like this.
ng-options="u.id as u.first_name for u in users"
$scope.selectedUser = data[0].id;