Angular Select value not changing - angularjs

I have several rows in a table, each having a select menu in the last cell. The initial value is populated by one controller and the select options being populated by a second controller. The second controller also updates the value on ng-change. If I use ng-selected, I get the initial value but does not change the value on change. (it does log it to the console though). If I use ng-init, it does not give a value on load, but does update after changing the value.
app.controller('agents', function($scope, $http){
$scope.getAgents = function(){
$http.get("getagents.php").then(function(response) {
$scope.agents = response.data;
});
}
$scope.getActiveAgents = function(){
$http.get("activeagents.php").then(function(response) {
// console.log(response.data);
$scope.activeagents = response.data;
});
}
$scope.updateAgenttoLead = function(agent, id){
console.log('ID:'+ id);
console.log('Agent:'+ agent);
}
$scope.updateForm = {};
$scope.updateAgent = function() {
$http.post('updateagent.php', {
'id' : $scope.updateForm.id,
'username' : $scope.updateForm.username,
'password' : $scope.updateForm.password
}
).success(function(data) {
// console.log(data);
$scope.updateForm = {};
$scope.getAgents();
// if (!data.success) {
// // if not successful, bind errors to error variables
// $scope.errorName = data.errors.name;
// $scope.errorSuperhero = data.errors.superheroAlias;
// } else {
// // if successful, bind success message to message
// $scope.message = data.message;
// }
});
};
$scope.addForm = {};
$scope.addAgent = function() {
$http.put('createagent.php', {
'username' : $scope.addForm.username,
'password' : $scope.addForm.password,
'type' : $scope.addForm.type
}
).success(function(data) {
$scope.addForm = {};
$scope.getAgents();
});
};
$scope.deleteagent = function(newid){
var r =confirm('Are you sure you want to delete '+ newid+'?');
if(r){
$http.post('deleteagent.php', {
'newid':newid
}
).success(function(data) {
$scope.getAgents();
console.log(data);
});
}
};
}); // end controller
app.controller('leads', function($scope, $http){
$scope.getLeads = function(){
$http.get("getleads.php").then(function(server) {
$scope.leads = server.data;
});
}
$scope.dispositions =[
'Never Called',
'Not Available',
'Left Message',
'Call Later',
'Not Interested',
'Not Qualified',
'Bad Phone',
'No Dates',
'DNC',
'Post Date',
'Sold'
];
$scope.updateDisp = function(disp, id){
var r = confirm('Update record '+ id +' to '+disp+'?');
if(r){
$http.post('updatedisp.php', {
'id' : id,
'disp' : disp
}
).success(function(data) {
console.log(data);
});
}else{
$scope.leads={};
$scope.getLeads();
}
}
}); // end controller

You are using controllers as services. Controllers are meant to be used as a way to bind a UI to implementation, not to provide functionality for retrieving data.
I would refactor your code to have a single controller for your page/table and then put all of this agent/leads code in separate services that your controller then consumes when needed.
See this blog post for more insight:
http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/

Related

Creating new function in angularjs controller won't work

When creating new function in angularjs controller and assign it to button with ng-click and function is simple,
function toLogin() {
console.log("Entered function");
$state.go('login');
}
I tried with $scope and still does not work.
this is my controller:
'use strict';
angular.module('crudApp').controller('UserController',
['UserService', '$scope','$state', function( UserService, $scope, $state) {
var self = this;
self.user = {};
self.users=[];
self.user.enabled = false;
self.user.confirmationToken = '';
self.loggedUser = null;
self.submit = submit;
self.getAllUsers = getAllUsers;
self.createUser = createUser;
self.updateUser = updateUser;
self.removeUser = removeUser;
self.editUser = editUser;
self.reset = reset;
self.firstNamePattern=/^[A-Z][a-z]*\S$/;
self.lastNamePattern=/^[A-Z][a-z]*\S$/;
self.userNamePattern= /^\S*$/;
self.passwordPattern = /^\S*$/;
self.phonePattern = /^[0-9]+\S$/;
self.successMessage = '';
self.errorMessage = '';
self.done = false;
self.onlyIntegers = /^\d+$/;
self.onlyNumbers = /^\d+([,.]\d+)?$/;
function toLogin() {
console.log('Entered function');
// $state.go('login');
}
function submit() {
console.log('Submitting');
if (self.user.id === undefined || self.user.id === null) {
console.log('Saving New User', self.user);
createUser(self.user);
} else {
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
}
$scope.moje = function () {
console.log('Submitting');
if (self.user.id === undefined || self.user.id === null) {
console.log('Saving New User', self.user);
createUser(self.user);
} else {
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
}
function createUser(user) {
console.log('About to create user');
UserService.createUser(user)
.then(
function (response) {
console.log('User created successfully');
self.successMessage = 'User created successfully';
self.errorMessage='';
self.done = true;
self.user={};
$scope.registerForm.$setPristine();
$scope.registerForm.$setUntouched();
// $state.reload();
},
function (errResponse) {
console.error('Error while creating User');
self.errorMessage = 'Error while creating User: ' + errResponse.data.errorMessage;
self.successMessage='';
}
);
}
function updateUser(user, id){
console.log('About to update user');
UserService.updateUser(user, id)
.then(
function (response){
console.log('User updated successfully');
self.successMessage='User updated successfully';
self.errorMessage='';
self.done = true;
$scope.myForm.$setPristine();
},
function(errResponse){
console.error('Error while updating User');
self.errorMessage='Error while updating User '+errResponse.data;
self.successMessage='';
}
);
}
function removeUser(id){
console.log('About to remove User with id '+id);
UserService.removeUser(id)
.then(
function(){
console.log('User '+id + ' removed successfully');
},
function(errResponse){
console.error('Error while removing user '+id +', Error :'+errResponse.data);
}
);
}
function getAllUsers(){
return UserService.getAllUsers();
}
function editUser(id) {
self.successMessage='';
self.errorMessage='';
UserService.getUser(id).then(
function (user) {
self.user = user;
},
function (errResponse) {
console.error('Error while removing user ' + id + ', Error :' + errResponse.data);
}
);
}
function reset(){
self.successMessage='';
self.errorMessage='';
self.user={};
$scope.myForm.$setPristine(); //reset Form
}
}
]);
And and I using ui-routing and this is where I assign controller to my view:
}).state('success',{
url: '/success',
templateUrl: 'partials/successMessage',
controller: 'UserController',
controllerAs: 'sCtrl'
});
And the ftl part of code is here:
<button type="button" ng-click='sCtrl.toLogin()' class="btn btn-primary">Login</button>
It won't even print to console, but when assigning older function it works perfectly, although it is much more complicated. Ps. Sorry for bad clarification at first, I am new to community and still learning a proper way to ask question.
You're not registering the method to the controller, to do that.
Add this below in self.onlyNumbers
self.toLogin = toLogin;
You need to use $scope
$scope.toLogin = function(){
console.log("Entered function");
$state.go('login');
}

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Ionic Infinite Scroll with http.post results

I am trying to create an infinite scroll based on Gajotres post (http://www.gajotres.net/ionic-framework-tutorial-11-infinite-scroll/)
My problems are:
If i write : $scope.searchObjects($scope.formData); all $scope objects are printed on the screen, how can it be avoided?
Can i pass form data by using $scope.formData, this way: .
$scope.searchObjects($scope.formData);
Until now the list freezes with 7000 itens and can not get the infinite scroll to work , seems it load all the itens.
There is a better know solution to ionic infinite scroll with http.post ?
Here is my attempt code any help would be apreciated :
.controller('someObjectsCtrl', function( $scope, $http) {
$scope.data = null;
$scope.itens = [];
$scope.data = {
'state' : '',
'city' : '',
}
$http.get('http://someservice.com/states.php').then( function response(response){
$scope.states = response.data;
},function(error){
$scope.error = JSON.stringfy(error);
});
$scope.getCities = function(id) {
$http.get('http://someservice.com/state.php?stateid='+id).then( function response(result) {
$scope.cities = result.data;
$ionicLoading.hide();
},function(error) {
$scope.error = JSON.stringfy(error);
});
};
$scope.originForm = angular.copy($scope.data);
$scope.searchObjects = function(data) {
$scope.formData = {};
$scope.formData.state = data.state;
$scope.formData.city = data.city;
$http.post("http://someservice.com/objectsToSearch.php", $scope.formData )
.success( function(data) {
$scope.result = data;
for (var i = 0; i <= 6; i++) {
$scope.itens.push({ foundObjects: $scope.result.OBJECTS});
}
$scope.$broadcast('scroll.infiniteScrollComplete');
if( $scope.result.length == 0 ){
$scope.data = null;
}
$scope.headers = ['Some Objects', 'Another Objects' ];
})
.error(function(error){
$ionicLoading.show({ template: '<p>Error ...</p>',duration :6000 });
})
}
$scope.canWeLoadMoreContent = function() {
return ($scope.itens.length > 10) ? false : true;
console.log(' scope.itens.length '+$scope.itens.length );
}
$scope.searchObjects($scope.formData);
})
Until now the only solution i find was to use collectio-repeat instead of ng-repeat. Collection-repeat is very fast rendering the result list.

error performing a get request

I am trying to perform a get request, in the post request everything is OK, I can see that in the post request all I do it's been save, once I refresh the page I am printing in the console the items saved by the post request, but those items aren't been return with the get I am doing.
here is where everything begins, I have a list of items here with the option to checked or unchecked the items in the list
<ion-item ng-repeat="sport in sports" ng-click="toggleSportSelection(sport)">
{{:: sport.name}}
</ion-item>
all the items are checked = true by default, so what I am saving, are the items with checked = false, the items checked = true you can see them here
<div ng-show="sport.checked" ng-repeat="sport in sports">
{{sport.name}}
</div>
this is what I have in the controller
.controller('SportsController', function($scope, SportsFactory) {
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sport, 'id'),
intersectedSports = _.intersection(sport.id, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}, function(err) {
console.log(err);
});
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
// this is what puts the sports on checked = true
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
and this is the service / factory
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
});
I am working along with NodeJS, so if you want the code I have in that part just let me know, so far I think that the issue I have is in the front end part, in the controller.

is invoking a service into another service in angular

I need to save data and then I need to dispaly the changes immediately afterwards.
That's why I Have a
updateSaisine which allows me to update data
getOneSaisine which allows me get the data and display them:
Which is the more correct way and for which reasons ?
Should I write:
$scope.saveSaisine = function() {
saisineSrv.updateSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).
then(
function() {
$scope.errorMessages = [];
if ($scope.currentSaisine.idMotif) {
toaster.pop('success', 'Réponse', 'Success');
angular.element('#modalSaisine').modal('hide');
saisineSrv.getOneSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).then(function(response) {
$scope.currentSaisine.dateModif = response.dateModif;
});
},
function error(response) {
$scope.errorMessages = response.data;
toaster.pop('error', 'Réponse', 'We have a problem');
}
);
};
OR
$scope.saveSaisine = function() {
saisineSrv.updateSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).
then(
function() {
$scope.errorMessages = [];
if ($scope.currentSaisine.idMotif) {
toaster.pop('success', 'Réponse', 'Success');
angular.element('#modalSaisine').modal('hide');
},
function error(response) {
$scope.errorMessages = response.data;
toaster.pop('error', 'Réponse', 'We have a problem');
}
);
saisineSrv.getOneSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).then(function(response) {
$scope.currentSaisine.dateModif = response.dateModif;
});
};
the first option is a correct way how you should refresh your data because these services are asynchronous thus in the second example you may don't get fresh data (the getOneSaisine can finish before updateSaisine).

Resources