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
};
Related
I'm trying to put pagination with ng-repeat. Getting result but by the time showing old data and suddenly hide and show new set data, like jerking. My angularjs version is "1.5.8".
$scope.gap = 5;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
var resultData = [...];
var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};
// init the filtered items
$scope.search = function () {
$scope.filteredItems = $filter('filter')(resultData, function (item) {
for(var attr in item) {
if (searchMatch(item[attr], $scope.query))
return true;
}
return false;
});
// take care of the sorting order
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
console.log($scope.pagedItems)
};
$scope.range = function (size,start, end) {
var ret = [];
//console.log(size,start, end);
if (size < end) {
end = size;
start = size-$scope.gap;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
// console.log(ret);
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
console.log($scope.pagedItems[$scope.currentPage]);
$scope.currentPage = this.n;
};
$scope.search();
html
<tr ng-repeat="user in pagedItems[currentPage]" >
<td>{{user.name}} {{$index}}</td>
</tr>
As above code, that table row update as 5 row. but when I click next or page numbers showing 10 rows and hide 5 rows. I hope you understand guys! Help me.
In my opinion you are thinking wrong, it's simpler to use custom filter and break up your business logic like this
app.filter('startFrom', function() {
return function(input, start) {
start = +start;
return input.slice(start);
}
});
then in the controller you can do
$scope.showResults = function() {
$scope.list = $filter('startFrom')($scope.initialList, $scope.page * $scope.itemsPerPage);
$scope.list = $filter('limitTo')($scope.list, $scope.itemsPerPage);
}
};
now you need only to update $scope.page and reuse $scope.showResults() to update the view
<tr ng-repeat="user in list" >
<td>{{user.name}} {{$index}}</td>
</tr>
I don't think that your problem is cause by ng-repeat. I just take your code, add some dummy data and do a test and it's totally work fine.
You can check it here https://codepen.io/Cushdrive/pen/zvPPXd
Because angular is two way binding, so I'm wonder that could it be some paging info was triggered somewhere. Could you double check on some variable like currentPage itemPerPages or pagedItems to see if it being used somewhere else?
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') || [];
I have a problem with this pagination code. I have 1 button instead of 3. Can you help?
paginator.js
$scope.generateButtons = function () {
var buttons = [],
pageCount = getPageCount(),
buttonCount;
console.log("page " + pageCount);
buttonCount = pageCount > 2 ? 3 : pageCount;
for (var i = 0; i < buttonCount; i++) {
var index = +$scope.offset + i -1;
if (index > 0) {
buttons.push(index);
}
};
return buttons;
};
View in plunker
My suggestion is to use Angular UI bootstrap pagination, and not write it from scratch https://angular-ui.github.io/bootstrap/#/pagination
angular.module('ui.bootstrap.demo').controller('PaginationDemoCtrl', function ($scope, $log) {
$scope.totalItems = 64;
$scope.currentPage = 4;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
$log.log('Page changed to: ' + $scope.currentPage);
};
$scope.maxSize = 5;
$scope.bigTotalItems = 175;
$scope.bigCurrentPage = 1;
});
It's really not about angular related problem. Its all about the logic for $scope.generateButtons = function () {...} Please change your logic as you need. Here is your code (edited) for displaying 3 buttons.
$scope.generateButtons = function () {
var buttons = [],
pageCount = getPageCount(),
buttonCount;
buttonCount = pageCount > 2 ? 3 : pageCount;
for (var i = 0; i < buttonCount; i++) {
var index = parseInt($scope.offset) + i+1;
if (index >= 0) { // this `if` is not really needed
buttons.push(index);
}
};
return buttons;
};
Enjoy!
My HTML has a loop with ng-repeat:
<div class="row">
<div ng-repeat="item in model.painel track by item.codigoIncidente">
<strong>{{item.restante.horaMinutoSegundo}}</strong>
</div>
</div>
My controller has a $interval that decrement horaMinutoSegundo.
nihilApp.controller('IncidentePainelController', ['$scope', '$interval', 'Incidente', function ($scope, $interval, Incidente) {
$scope.model = {
painel: [],
};
var find = function() {
Incidente.listPainel({pagina: 0}).$promise.then(function (result) {
$scope.model.painel = result.pagedList;
$scope.model.totalItems = result.totalGeral;
}, function (error) {
console.log(error);
});
};
var updateTime = function() {
for (var i = 0; i < $scope.model.painel.length; i++) {
if ($scope.model.painel[i].status.id === 'E' && $scope.model.painel[i].restante.segundos > 0) {
var segundos = $scope.model.painel[i].restante.segundos - 1;
$scope.model.painel[i].restante.horaMinutoSegundo = getHoraMinutoSegundo(segundos);
}
}
};
var getHoraMinutoSegundo = function (segundos) {
var horaMath = Math.floor(segundos / 3600);
var remMath = Math.floor(segundos % 3600);
var minutoMath = Math.floor(remMath / 60);
var segundoMath = Math.floor(remMath % 60);
var hrStr = (horaMath < 10 ? "0" : "") + horaMath;
var mnStr = (minutoMath < 10 ? "0" : "") + minutoMath;
var secStr = (segundoMath < 10 ? "0" : "") + segundoMath;
return hrStr.concat(":").concat(mnStr).concat(":").concat(secStr);
};
$interval(updateTime, 1000);
find();
}]);
But the {{item.restante.horaMinutoSegundo}} does not update in HTML. Can someone help me with this problem ? Thanks a lot!
https://jsfiddle.net/araraujo/96w3jrrh/
It should work, but you have a little mistake in your code.
var segundos = $scope.model.painel[i].restante.segundos - 1;
You put new segundos value into a variable, but you didn't update the one from scope.
Here is the fiddle with the updated version
There are two things you need to change
inject $interval in your controller
app.controller('MainCtrl', function($scope, $interval) {
}
Update your model so that it match the with your logic inside for loop. Something like below.
$scope.model = {
painel: [{restante : 1 }] }
you must add $scope.apply at the end.
var updateTime = function() {
for (var i = 0; i < $scope.model.painel.length; i++) {
if ($scope.model.painel[i].status.id === 'E' && $scope.model.painel[i].restante.segundos > 0) {
var segundos = $scope.model.painel[i].restante.segundos - 1;
$scope.model.painel[i].restante.horaMinutoSegundo = getHoraMinutoSegundo(segundos);
}
}
$scope.apply();
};
Found the gap, replace this line
var segundos = $scope.model.painel[i].restante.segundos - 1;
With
scope.model.painel[i].restante.segundos = $scope.model.painel[i].restante.segundos - 1;
I declare $scope.something in my controller like
app.controller('MainControl', function($scope){
$scope.something = 1;
});
then how can I access it in my filter scope? like
app.filter("myCustomFilter", function () {
// here
});
obviously it doesn't work if I just $scope.something there.
After a chat here is the working solution http://jsbin.com/juxebewu/4/edit
<div ng-controller="sCtr">
<ul>
<li>{{aa | friends:this}}</li></ul>{{showItem}}
<p ng-show="showItem">click</p>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
var app = angular.module('App', []);
var targetOfFriendTasks = 1;
var user = [];
user[0]= {uId: 1};
app.filter("friends", function () {
return function (input, s) {
var output = [];
for (var i in input) {
if (input[i].name.length >= 1 && input[i].uId == targetOfFriendTasks) {
output.push(input[i]);
}
}
if (targetOfFriendTasks != user[0].uId) {
return output;
} else {
s.showItem = true;
}
};
});
app.controller('sCtr', function ($scope) {
$scope.aa = [{name:"lorem", uId:1}, {name:"ipsum", uId:2}];
$scope.showItem = false;
});