Initialize select box with the retrieved id - angularjs

I am new to angular js and I am trying to code an edit page which contains a select box. It has id as the value and name as the display label.
<select class="form-control" ng-model="item.user"
ng-options="user.id as user.loginName for user in Users" ng-disabled="true" >
<!-- ng-init="item.user=userId" -->
<option value="">Select User</option>
</select>
As I am adding edit page, I retrieve the values from server side and it returns the id for the select box. When I used ng-init to set the value (See the commented ng-init code), it displays only the Select User option. When I manually provide a user id like
ng-init="item.user=3"
The corresponding user is displayed correctly in the select box. I tried setting the value from controller as,
$scope.item.user = result.userid;
alert($scope.item.user);
The alert doesn't throw but when I alert result.userid above it, it works fine. What could be the problem?
EDIT 1:
Sample controller(controller.js):
function SampleController(Sample, $scope, $http,$compile, $filter, $modal, $timeout, DTOptionsBuilder, DTColumnBuilder,DTInstances) {
$scope.edit = function(id) {
//Retrieves value for dropdown
selectbox.userList(function(result) {
$scope.Users = result.content;
});
// alert("EDIT action initiated ID : " + id);
var params = {
id : id
};
$scope.sampleObj= Sample.view(params, function() {
$scope.$state.go('sampleEdit', {id:id});
});
}
}
state (config.js):
.state('admin.editSample', {
url: '/editSample/:id',
templateUrl: 'sample/editSample.html',
data: { pageTitle: 'Edit Sample'},
controller: SampleEditController
})
SampleEditController(controller.js):
var sampleEditController = function($stateParams, $scope, $http){
var params = {};
params.id = $stateParams.id;
var url = "sample/edit";
$http.get(url, {
params : params
}).success(function(result) {
alert("Users: " + $scope.Users); //Here it alerts undefined
for(var i = 0; i < $scope.Users.length && !$scope.item.user;i++){
if ($scope.Users[i].id === result.id) {
$scope.item.user = $scope.Users[i];
}
}
})
Edit 2:
SampleRepository
#Repository
public interface IUserRepository extends JpaRepository<Employee, Long>{
#Query("select new com.sample.application.model.dto.SampleInfo(c.id,e.fullName,"
+ "c.accountExpired,c.accountLocked,c.rowCreated,c.enabled,c.rowAltered, c.password, c.passwordExpired, c.loginName, c.languageFluency) "
+ " from Employee c left join c.person e order by c.id asc")
Page<IUserInfo> getList(Pageable pageable);
}
Edit 3:
services.js
.factory('sample', ['$http', function ($http) {
return {
userList : function(result){
$http.get('sample/list').success(result);
} }
I also tried this inside the controller,
userRoleEditController:
$http.get(url, {
params : params
}).success(function(res) {
selectbox.userList(function(result) {
$scope.User = result.content;
for(var i = 0; i < $scope.User.length; i++){
if ($scope.User[i].id === res.empId) {
$scope.item.user = $scope.User[i];
}
}
});
})
With this I am able to get $scope.User. I tried alerting $scope.item.user after $scope.item.user = $scope.User[i]; but it didn't work and i didn't get the value in the drop down box.

ng-init shouldn't be used to initilise as mentioned in the documentation. Instead to set the selected item set item.user in the controller.
To get the user with id as 3 you will need to loop through the users until you find the correct user. Once found set $scope.item.user to the user:
for (var i = 0; i < $scope.Users.length && !$scope.item.user; i++) {
if ($scope.Users[i].id === 3) {
$scope.item.user = $scope.Users[i];
}
}
Edit:
In your service return the promise from $http:
.factory('sample', ['$http', function ($http) {
return {
userList : function(){
return $http.get('sample/list');
}
}
}
Then in your controller where this is called you would do something like this to call this service method, handle the promise, set the users and the user on $scope:
sample.userlist().then(function (response) {
$scope.Users = response.data;
for (var i = 0; i < $scope.Users.length && !$scope.item.user; i++) {
if ($scope.Users[i].id === 3) {
$scope.item.user = $scope.Users[i];
}
}
});

Related

AngularJS Custom filter using radio button

<div ng-repeat="item in places">
<input type="radio" name="rdnPriority" value="{{item}}" ng-checked="exists(item,selected)" ng-click="toggle(item,selected)" >{{item}}<label>
var app = angular.module("myModule", ['ngMaterial', 'ngMessages']);
app.controller("GetTicketDetails", function ($scope, $http, $interval) {
$scope.GetOrders = function () {
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
//alert(url);
debugger;
$http({
url: "../api/GetOrderDetailByDate",
method: "GET"
}).then(function (response) {
console.log(response.data);
$scope.ListTicketDetails = response.data;
$scope.TotalTickets = response.data.length;
$scope.selected = [];
$scope.places = [];
// when user clicks on checkbox, change selected list
$scope.toggle = function (item, list) {
var idx = list.indexOf(item);
if (idx > -1) list.splice(idx, 1);
else list.push(item);
};
// is item exists in list
$scope.exists = function (item, list) {
debugger;
debugger;
if (scope.checked == item) {
scope.checked = false;
}
return list.indexOf(item) > -1;
};
// process user data and prepare whole places
angular.forEach($scope.ListTicketDetails, function (x, key) {
if ($scope.places.indexOf(x.OrderStatus) == -1) {
//$scope.recordLimit = 5;
$scope.places.push(x.OrderStatus);
}
});
}
app.filter('SelectedTags', function () {
// filter to check array of elements
return function (users, tags) {
return users.filter(function (x) {
if (tags.indexOf(x.OrderStatus) != -1) {
return true;
} else if (tags.length == 0) {
return true;
}
return false;
});
};
})
Hello , I have written a AngularJS Custom filter that filters the orders based on status using RadioButton Check . The problem is data is filtering but Radio Button I need to double click one click for Uncheck existing checked and next check othr status . Is there a way i can achieve that with just single check on there options of radio button .
{{Item}} is filtering all orderstatus from array and rendering radio button Inputs options.
Please help

No popup window with AngularJS and typeahead

I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};

how to connect 2 objects in ionic via backand

i need a bit of help to my ionic project. so i want to connect 2 objects in ionic, so that i can display the value of and object that has data from the other object.
<ion-list class="list-inset">
<ion-item class="item-text-wrap" ng-repeat='item in todos| filter:firma'>
<h2>{{item.company_name}}</h2>
</ion-item>
<ion-item class="item-text-wrap" ng-repeat='item in todos2 | filter:{ idcompany:com_id } '>
<h2>ponedeljek {{item.time_mon_start}}-{{item.time_mon_end}}</h2>
<h2>torek {{item.time_tue_start}}-{{item.time_tue_end}}</h2>
<h2>sreda {{item.time_wed_start}}-{{item.time_wed_end}}</h2>
<h2>Ĩetrtek {{item.time_thu_start}}-{{item.time_thu_end}}</h2>
<h2>petek {{item.time_fri_start}}-{{item.time_fri_end}}</h2>
<h2>sobota {{item.time_sat_start}}-{{item.time_sat_end}}</h2>
<h2>nedelja {{item.time_sun_start}}-{{item.time_sun_end}}</h2>
</ion-item>
this is what i want to display for the current company that i click on, but it shows all the times not only one that i want.
.controller('AppCtrl', function($scope, TodoService, cas, $state) {
$scope.todos = [];
$scope.todos2 = [];
function getAllTodos() {
TodoService.getTodos().then(function (result) {
$scope.todos = result.data.data;
$scope.firma = $state.params.aid;
});
}
getAllTodos();
function getalltimes() {
cas.getcompany().then(function (result) {
$scope.todos2 = result.data.data;
});
}
getalltimes();
})
.service('TodoService', function ($http, Backand, $state) {
var baseUrl = '/1/objects/';
var objectName = 'companies/';
function getUrl() {
return Backand.getApiUrl() + baseUrl + objectName;
}
function getUrlForId(id) {
return getUrl() + id;
}
getTodos = function () {
return $http.get(getUrl());
};
return {
getTodos: getTodos
}
})
.service('cas', function ($http, Backand, $state) {
var baseUrl = '/1/objects/';
var time = 'companies_timetable/';
function getUrl2() {
return Backand.getApiUrl() + baseUrl + time;
}
getcompany = function () {
return $http.get(getUrl2());
};
return {
getcompany: getcompany
}
})
this is now my app.js file and my connection to the backand service. this is working fine.
this are the companys from object 1
and this are the times showing
so when you click on the companys it should show the time for it. but here it shows all times that are in the object. i should show only one for the one company
i was trying to give all objects in one array (todos). but didn't worked rlly well. so please i need some help. if you need some more code or somthing just say it :).
Your second filter is wrong.
Simplest way to fix it is to call a function in $scope.
Change your filter like this:
<ion-item class="item-text-wrap" ng-repeat='item in todos2 | filter: isCurrentFirma '>
Then add a function in your controller:
$scope.isCurrentFirma = function(item){
// here check if item is equal to firma
// code like this:
return item.idcompany === $scope.firma.com_id
}

Linking user's contacts in firebase with md-contacts-chips

I am having difficulty getting my head around on how I could link my users contacts in Firebase with md-contacts-chips from https://material.angularjs.org/0.11.2/#/demo/material.components.chips
Basically, each registered user can add people they know via email to their contacts list. The users firebase structure is as follows:
firebase
-$uid1
contacts
$uid2 - userObject
$uid3 - userObject
-$uid2
contacts
$uid1 - userObject
$uid3 - userObject
-$uid3
contacts
$uid1 - userObject
$uid2 - userObject
etc..
Is it possible to ng-repeat a users contacts as an array of objects?
How should I configure the md-contacts-chip?
The example has a function called loadContacts() which has the contacts set.
How would I be able to set my user objects as contacts? The return object is contact and I would like to find a way for it to return the queried object.
function loadContacts() {
var contacts = [
'Marina Augustine',
'Oddr Sarno',
'Nick Giannopoulos',
'Narayana Garner',
'Anita Gros',
'Megan Smith',
'Tsvetko Metzger',
'Hector Simek',
'Some-guy withalongalastaname'
];
return contacts.map(function (c, index) {
var cParts = c.split(' ');
var contact = {
name: c,
email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase() + '#example.com',
image: 'http://lorempixel.com/50/50/people?' + index
};
contact._lowername = contact.name.toLowerCase();
return contact;
});
}
Thanks
I'm by no means an expert, just a trial and error fanatic. That being said I did get this to work. I the issues is that "md-contact-chip" uses "push and splice" to adjust the array, and as firebase states that's a bad idea. If we had access to replace push with $add() or splice with $remove() this should work properly.
I was looking at the custom chips setup and it seems possible because you can call a function during the chip's add and remove, then with a custom chip template could maybe get the same look as the contact-chips.
Anyway here is what I did to get it working with md-contact-chips. Also I've adjusted this one to work with a list of items, not contacts, cause I wanted the picture for the items.
The key to it should be get your whole person obj, then set the ng-model="ctrl.person.contacts" inside the controller make sure to have an array created if person.contacts does not exist. "ctrl.person.contacts = ctrl.person.contacts || [];
Yes your are not properly updating the firebase object but you when you run
ctrl.person.$save() you are just completely updating the db.
Html
<div layout="column" ng-cloak>
<div>
<p>Items selected</p>
<pre>{{ctrl.item.installedItems}}</pre>
</div>
<input type="button" ng-click="ctrl.updateInstalledItems()" value='update'>
<md-content class="md-padding autocomplete" layout="column">
<md-contact-chips
ng-model="ctrl.item.installedItems"
md-contacts="ctrl.querySearch($query)"
md-contact-name="alseSn"
md-contact-image="image"
md-require-match="true"
md-highlight-flags="i"
filter-selected="ctrl.filterSelected"
placeholder="Select installed items">
</md-contact-chips>
</md-content>
</div>
Controller
app.controller('ItemChipCtrl', ['items', 'item', '$q', '$log',
function (items, item, $q, $log) {
var ctrl = this;
ctrl.items = items;
ctrl.item = item;
ctrl.item.installedItems = ctrl.item.installedItems || [];
ctrl.querySearch = querySearch;
ctrl.allItems = loadItems(ctrl.items);
ctrl.filterSelected = true;
ctrl.updateInstalledItems = function() {
$log.info('Update....')
$log.log(ctrl.installedItems);
ctrl.item.$save();
}
/**
* Search for contacts.
*/
function querySearch (query) {
var results = query ?
ctrl.allItems.filter(createFilterFor(query)) : [];
return results;
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.alseSn.indexOf(lowercaseQuery) != -1);
};
}
function loadItems(items) {
/*var items = $scope.items */
return items.map(function (c, index) {
var item = {
alseSn: c.alseSn || c,
alseCard: c.alseCard,
installedOn: c.installedOn || null,
image: 'img/items/47/'+c.alseCard+'.jpg' || null
};
return item;
});
}
}
]);
route injections
.when('/settings/:alseSn', {
templateUrl: 'settings.html',
controller: 'ItemChipCtrl as ctrl',
resolve: {
auth: function($location, Auth){
return Auth.$requireAuth().then(function(auth) {
return auth;
},function(error){
$location.path('/login');
});
},
item: function($route, Items, Auth){
return Auth.$requireAuth().then(function(){
return Items.getItem($route.current.params.alseSn).$loaded();
});
},
items: function(Items, Auth){
return Auth.$requireAuth().then(function(){
return Items.all.$loaded();
});
}
}
})

MEAN with Jade template form submit GET instead of POST

So, earlier today I had a working form that could post and delete restaurants documents to a mongodb collection. Everything was working fine, but then I decided to try and load the form into a div instead of redirect to a new page. Doing so produced a different result when I tried to submit my restaurant form. Originally it would call $scope.add() in my restaurantsController, but now it is sending a GET request with form data to /restaurants instead of a POST to /api/restaurants. I'm looking for some insight as to what I did to change the behavior. Although it is loading the form when I click on my restaurant anchor tag, it is not loading the restaurants from the database.
Here is the jade and js for the menu anchors:
menu.js
app.controller("menu", ["$scope", "$http", function ($scope, $http) {
$scope.home = function () {
$("#content").html("");
};
$scope.restaurants = function () {
$http.get('/restaurants').
success(function(data, status, headers, config){
$("#main_content").html(data);
}).
error(function(data, status, headers, config){
});
};
}]);
nav.jade
mixin link(name, fn)
li
a.btn(ng-click=fn)= name
nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
.container
.navbar-header
button.navbar-toggle.collapsed(type='button', data- toggle='collapse', data-target='#navbar', aria-expanded='false', aria- controls='navbar')
span.sr-only Toggle navigation
span.icon-bar
span.icon-bar
span.icon-bar
a.navbar-brand(href='/') Food App
#navbar.navbar-collapse.collapse
ul.nav.navbar-nav(ng-controller="menu")
+link("Home", "home()")
+link("Restaurants", "restaurants()")
And here is the form:
form(name="NewRestaurant" ng-submit="$event.preventDefault();add()")
.row
.form-group
input.form-control(type="text", name="name" placeholder="Name", ng-model="name" required)
.row
.form-group
input.form-control(type="text", name="address" placeholder="Address", ng-model="address" required)
.row
.form-group.col-md-6
-for(var i = 0; i <= 5; i++){
input(name="rating" type="radio", value=i, ng-model="rating" required)
=i
-}
.form-group.col-md-6
button.success(type="submit") Submit
and the controller...
app.controller("restaurants", ["$scope", "$resource", function ($scope, $resource) {
var Restaurant = $resource('/api/restaurants/:id');
var clearForm = function () {
$scope.name = '';
$scope.address = '';
$scope.rating = null;
}
clearForm();
var validRestaurant = function () {
if($scope.name !== '' && $scope.address !== '' && $scope.rating !== null)
return true;
else{
toastr.error("Please fill in all required form fields.");
return false;
}
}
$scope.query = function(){
Restaurant.query(function (results) {
$scope.restaurants = results;
});
};
$scope.add = function () {
alert("got here!");
if(validRestaurant()){
var restaurant = new Restaurant();
restaurant.name = $scope.name;
restaurant.address = $scope.address;
restaurant.rating = $scope.rating;
alert(restaurant);
Restaurant.save(restaurant, function (result) {
$scope.restaurants.push(result);
toastr.success("Saved " + $scope.name + ".")
clearForm();
});
}
};
$scope.update = function (id) {
};
$scope.remove = function (id) {
console.log(id);
Restaurant.delete({id: id}, function (err) {
console.log(err);
$scope.query();
});
};
$scope.query();
}]);
edit: Now that I am typing this up, I am wondering, maybe angular doesn't recognize the form and doesn't create a $scope for it because it gets loaded after the page loads...?

Resources