How to get a $scope value inside a function with angularjs - javascript

I have a pagination code which I should use repeatedly inside the same controller and thought of putting it inside a function. But it is not working as I expected. Always sends an error saying some value is undefined.
How do I achieve this.
(function () {
'use strict';
angular
.module('efutures.hr.controllers.creation', [])
.controller('UserCreateController', UserCreateController);
UserCreateController.$inject = ['$scope', '$location', '$rootScope', '$http', 'deptService', 'DeptNameService','EmployeeService'];
function UserCreateController($scope, $location, $rootScope, $http, deptService, DeptNameService, EmployeeService) {
(function initController() {
deptService.getdepts(function (res) {
$scope.depts = JSON.parse(res.data);
});
EmployeeService.GetEmpDetails(function (res) {
$scope.FilterDetails = JSON.parse(res.data); //This is the variable that I need inside the function.
$scope.PaginationTrigger($scope.FilterDetails); //CODE APPLIED HERE
});
})();
$scope.reset = function () {
$('#depts').val('').trigger('change.select2');
EmployeeService.GetEmpDetails(function (res) {
$scope.FilterDetails = JSON.parse(res.data);
});
};
$scope.paginationTrigger =function(details){ //This method is used to control the pagination
$scope.nums = ["10", "20", "30"];
$scope.viewBy = $scope.nums[0];
$scope.totalEmployees = $scope.details.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewBy;
$scope.maxSize = 5;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function () {
console.log('Page changed to: ' + $scope.currentPage);
}
$scope.setEmployeesPerPage = function (num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1;
}
}
$scope.DropdownSelected = function (value) {
console.log(value.DeptName + ' Selected');
var DeptNameChanged = {
'Name': value
};
DeptNameService.DeptNameValue(DeptNameChanged, function (res) {
$scope.FilterDetails = JSON.parse(res.data);
$scope.PaginationTrigger($scope.FilterDetails); //CODE APPLIED HERE
});
};
}
})();
According to the above code the ERROR IS: angular.js:13642 TypeError:
Cannot read property 'length' of undefined
So how can I achieve this? help would be appreciated. Thanks

test = {"a" : 1}
details = "a"
alert(test[details])
Use, $scope[details].length since details is a parameter there.
$scope.paginationTrigger =function(details){ //This method is used to control the pagination
$scope.nums = ["10", "20", "30"];
$scope.viewBy = $scope.nums[0];
$scope.totalEmployees = $scope[details].length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewBy;
$scope.maxSize = 5;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function () {
console.log('Page changed to: ' + $scope.currentPage);
}
$scope.setEmployeesPerPage = function (num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1;
}
}
Pls look the code snippet, you will get the error.

I finally figured it out.This is what I tried to accomplish and it was successful. Special thanks to #Sravan for repeatedly trying to help me out. Also thank you all for you help.
So here's the code. Thought of sharing for learning.
//Create a function in the controller
function paginationTrigger(value) {
$scope.nums = ["10", "20", "30"];
$scope.viewBy = $scope.nums[0];
$scope.totalEmployees = value.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewBy;
$scope.maxSize = 5;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function () {
console.log('Page changed to: ' + $scope.currentPage);
}
$scope.setEmployeesPerPage = function (num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1;
}
}
/* Call the function in the desired palce.
In this case inside my service function */
EmployeeService.GetEmpDetails(function (res) {
$scope.FilterDetails = JSON.parse(res.data);
//pagination code
paginationTrigger($scope.FilterDetails); //Passing the value
});

Related

Can't display JSON-objects from session-storage in AngularJS

I'm having problem displaying a JSON-object named "currentSet" from session-storage. When I instead use a JSON-file from a folder everything works fine, which means the HTML-code is probably fine. I have narrowed the problem down to either the $scope.set or the loadQuiz-function and have tried several things, but can't get it to work. This is the relevant parts from the controller:
$scope.set = angular.fromJson(sessionStorage.getItem('currentSet')); //doesn't work
//$scope.set = 'data/konflikter.js'; //works
$scope.defaultConfig = {
'autoMove': true,
'pageSize': 1,
'showPager': false
}
$scope.onSelect = function (question, choice) {
question.choices.forEach(function (element, index, array) {
question.Answered = choice;
});
if ($scope.defaultConfig.autoMove == true && $scope.currentPage < $scope.totalItems) {
$scope.currentPage++;
}
else {
$scope.onSubmit();
}
}
$scope.onSubmit = function () {
var answers = [];
$scope.questions.forEach(function (question, index) {
answers.push({'questionid': question._id, 'answer': question.Answered});
});
$http.post('https://fhsclassroom.mybluemix.net/api/quiz/submit', answers).success(function (data, status) {
$location.path('/');
});
}
$scope.pageCount = function () {
return Math.ceil($scope.questions.length / $scope.itemsPerPage);
};
$scope.loadQuiz = function (data) {
$http.get(data)
.then(function (res) {
$scope.name = res.data.name;
$scope.questions = res.data.questions;
$scope.totalItems = $scope.questions.length;
$scope.itemsPerPage = $scope.defaultConfig.pageSize;
$scope.currentPage = 1;
$scope.$watch('currentPage + itemsPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredQuestions = $scope.questions.slice(begin, end);
});
});
}
$scope.loadQuiz($scope.set);
Ok I figured out what's wrong, you are loading file so you need to get file - or import it to get the contents that's why it works with your:
$scope.set = 'data/konflikter.js'; //works but combined with http request
If you wish to pass data from dataStorage you will need to change your loadQuiz not to have http request like this:
$scope.loadQuiz = function (res) {
$scope.name = res.data.name;
$scope.questions = res.data.questions;
$scope.totalItems = $scope.questions.length;
$scope.itemsPerPage = $scope.defaultConfig.pageSize;
$scope.currentPage = 1;
$scope.$watch('currentPage + itemsPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredQuestions = $scope.questions.slice(begin, end);
});
}
With the help of #pegla I was able to solve the problem like this:
$scope.loadQuiz = function () {
$scope.set = angular.fromJson(sessionStorage.getItem('currentSet'));
$scope.questionsetid = $scope.set.questions[0].questionsetid;
$scope.name = $scope.set.name;
$scope.questions = $scope.set.questions;
$scope.totalItems = $scope.set.questions.length;
$scope.itemsPerPage = $scope.defaultConfig.pageSize;
$scope.currentPage = 1;
$scope.$watch('currentPage + itemsPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredQuestions = $scope.questions.slice(begin, end);
});
}
$scope.loadQuiz();

How to reset count in AngularJs

I have a list with four items. Each item have a counter. When we click on the item, the count will increase. I want to reset the counter value by zero except the clicking item. This is the Demo.
var myApp = angular.module('myApp',[]);
var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
inc.count = inc.count + 1
};
}
You can try like this. Loop over all items and check if the clicked item is the current one: increment and for others set to 0.
Try DEMO
var myApp = angular.module('myApp',[]);
var jsonInfo = {"count":[{"name":"one",count:0} ,{"name":"two",count:0},{"name":"three",count:0} ,{"name":"four",count:0}]}
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
jsonInfo.count.forEach((item) => {
item.count = item.name === inc.name? inc.count + 1 : 0;
});
};
}
Try this;
function MyCtrl($scope) {
$scope.data =jsonInfo;
$scope.count = function (inc) {
for(i=0; i<jsonInfo.count.length; i++){
if(jsonInfo.count[i].name != inc.name){
jsonInfo.count[i].count = 0;
}
}
inc.count = inc.count + 1
};
}
function resetOherCount(inc) {
jsonInfo.count.map(function(oneEle) {
if (oneEle.name != inc.name) {
oneEle.count = 0
}
return oneEle;
});
}
$scope.count = function (inc) {
resetOherCount(inc);
inc.count = inc.count + 1
};

Ionic application error: array.push() is not a function

I created an application where I have controller and factory. I have an array inside of the factory where I want to push id of the element to this array. However, when I am trying to push element to array I got an error that
"favorites.push is not a function"
Below you can find my controller and factory. Thank you for reading:
Factory:
.factory('favoriteFactory',['$resource', 'baseURL','$localStorage', function ($resource, baseURL, $localStorage) {
var favFac = {};
var favorites = $localStorage.get('favorites', []);
favFac.addFavorites = function (index) {
for(var i=0; i<favorites.length; i++){
if(favorites[i].id == index)
return
}
favorites.push({id: index});
$localStorage.storeObject('favorites',favorites)
}
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
}
}
$localStorage.storeObject('favorites', favorites)
};
favFac.getFavorites = function () {
return $localStorage.getObject('favorites',[]);
};
return favFac
}])
Controller:
.controller('MenuController', ['$scope', 'menuFactory', 'favoriteFactory','baseURL', '$ionicListDelegate', 'dishes', '$localStorage',
function($scope, menuFactory,favoriteFactory, baseURL, $ionicListDelegate, dishes, $localStorage) {
$scope.baseURL = baseURL;
$scope.tab = 1;
$scope.filtText = '';
$scope.showDetails = false;
$scope.showMenu = true;
$scope.message = "Loading ...";
$scope.addFavorite = function (index) {
console.log("index:" +index);
favoriteFactory.addFavorites(index);
$ionicListDelegate.closeOptionButtons();
};
$scope.dishes = dishes;
$scope.select = function(setTab) {
$scope.tab = setTab;
if (setTab === 2) {
$scope.filtText = "appetizer";
}
else if (setTab === 3) {
$scope.filtText = "mains";
}
else if (setTab === 4) {
$scope.filtText = "dessert";
}
else {
$scope.filtText = "";
}
};
$scope.isSelected = function (checkTab) {
return ($scope.tab === checkTab);
};
$scope.toggleDetails = function() {
$scope.showDetails = !$scope.showDetails;
};
}])
I assume you are using ngStorage. The get method does not have a second parameter. Therefore, your attempt at returning a default value of [](empty array) is simply returning undefined and then you are attempting to push to undefined and not to an array.
The source code for ngStorage shows no second parameter for get:
https://github.com/gsklee/ngStorage/blob/master/ngStorage.js
So this line:
var favorites = $localStorage.get('favorites', []);
Should be this:
var favorites = $localStorage.get('favorites') || [];

How to remove and edit object from cookies in angularjs

I have a problem with remove and edit cookie object from $cookies in angularjs. I want to make a shop and I am adding products to $cookies global variable with putObject function (I didn't use put because I have more than one argument). I want to add function to remove and edit product from shop and remove and edit only one object from cookie. Please help me!
Here is a fragment of my code (I want to remove/edit object from 'products' cookie):
app.controller('Store', ['$scope', '$cookies', 'x2js', '$http',
function($scope, $cookies, x2js, $http){
this.products = $cookies.getObject('products');
if(!this.products) {
var self = this;
$http.get('assets/xml/products.xml').success(function(data) {
self.products = data.products.product;
for(var i = 0; i < self.products.length; i++) {
self.products[i].id = parseInt(self.products[i].id);
self.products[i].netto = self.products[i].netto + '.00';
self.products[i].tax = parseInt(self.products[i].tax);
self.products[i].brutto = parseFloat(self.products[i].brutto);
self.products[i].rating = parseInt(self.products[i].rating);
};
});
}
$scope.product = $cookies.getObject('product') || {};
$scope.$watch('product', function() {
$cookies.putObject('product', $scope.product);
}, true);
this.addProduct = function() {
if(this.countCategories() >= 2) {
if(this.validateForm()) {
var product = {
id: this.products.length + 1,
name: $scope.product.name,
code: $scope.product.code,
image: $scope.product.image,
netto: this.intToFloat($scope.product.netto, 2),
tax: $scope.product.tax,
brutto: this.calculatePriceBr(),
rating: parseInt(this.ratingChecked()),
category: this.categoryChecked(),
option: this.optionChecked(),
selected: $scope.product.selected
};
this.products.push(product);
$scope.product = {};
$cookies.putObject('products', this.products);
$('#product-add').modal('hide');
return true;
} else {
return;
}
} else {
return;
}
};
})();
Hope this is what you are looking for.
I've made a little test based on your code (simplified):
var app = angular.module('myApp', ['ngCookies']);
app.controller('Store', Store);
Store.$inject = ['$scope', '$cookies', '$http'];
function Store($scope, $cookies, $http) {
var vm = this;
vm.products = [];
vm.cart = [] ;
vm.inCookie =[];
$http.get('products.xml').success(function(data) {
vm.products = data;
for (var i = 0; i < vm.products.length; i++) {
vm.products[i].id = parseInt(vm.products[i].id);
vm.products[i].netto = vm.products[i].netto + '.00';
vm.products[i].tax = parseInt(vm.products[i].tax);
vm.products[i].brutto = parseFloat(vm.products[i].brutto);
vm.products[i].rating = parseInt(vm.products[i].rating);
};
});
this.addProduct = function(row) {
vm.cart.push(row);
$cookies.put('cart', JSON.stringify(vm.cart));
vm.inCookie = JSON.parse($cookies.get('cart'));
};
}
You can see here how to add and retrieve data from a cookie.
In this plunkr you can see it working.
https://plnkr.co/edit/ew1ePjzbMxjAqtgx8hzq?p=preview
Hope this helps.
Regards!

Error dealing with $q.all and promises in AngularJS

Given the following code:
function Ctrl($scope, $http, $q) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
};
};
$scope.$watch('name', search, true);
var done = $scope.getDetails = function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
return $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=1&per_page=100')]);
};
done.then(function (){
$scope.releases = data2.releases;
$scope.artist = data;
return $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json');
});
I'm getting the following console error:
TypeError: Object function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
return $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=...<omitted>... } has no method 'then'
at new Ctrl (file:///C:/Users/Zuh/Desktop/AngularJS%20Discogs/js/services.js:27:9)
Can anybody point me to where might the error be? I'm defining the .then after getDetails is executed...
Here's a working Plunker.
Here is your updated plunkr http://plnkr.co/edit/lTdnkRB1WfHqPusaJmg2?p=preview
angular.module('myApp', ['ngResource']);
function Ctrl($scope, $http, $q) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
console.log(arguments)
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
};
};
$scope.$watch('name', search, true);
var done = $scope.getDetails = function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
var q = $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=1&per_page=100')])
.then(function (ret){
//console.log(arguments)
$scope.releases = ret[1].data.releases;
$scope.artist = ret[0];
return $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json');
})
return q
};
}
To sum up fixes:
move $q.all().then() part into done method
pay more attention to what parameters handlers received in then part.

Categories