ngRepeat dont refresh when I change the values - AngularJS - angularjs

I'm doing a application to a calendar and I create a function that everytime change the values of my variable called "$scope.days", when I was using the version 1.0 didnt give error, but now the ngRepeat doesnt refresh, the new values go to the variable, but the ngRepeat dont show the new result...
$scope.loadMonth = function()
{
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
if(i < weekday)
$scope.days.push('');
else
$scope.days.push(day++);
}
};
my html:
<div class="day" ng-repeat="day in days"><p>{{ day }}</p></div>
If I put an alert after push new values, I can see the new values, but my ngRepeat doesnt refresh the results, I already try many things but didnt work. Somebody know the solution?

Not sure I understand what you are trying to achieve given the small sample of code you provided but if you look at this sample you'll see that it should update the display every time you click the click me text, just enter either 1,2, or 3 in the input area. you might want to check that looping logic of yours.
<html lang="en-US" ng-app="mainModule">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="mainController">
<input type="text" ng-model="monthModel" placeholder="enter 1 2 or 3"/>
<h1 ng-click="loadMonth(monthModel)">Click Me to Repeat</h1>
<span class="day" ng-repeat="day in days">{{ day }} , </span>
</div>
<script type="text/javascript">
var app = angular.module("mainModule", []);
app.controller("mainController", function ($scope) {
//$scope.monthModel = 1; // default some date
$scope.year = "2014";
$scope.months = [
{"name":"January", "qty":10},
{"name":"February", "qty":5},
{"name":"March", "qty":10},
];
$scope.loadMonth = function(monthModel)
{
$scope.month = monthModel;
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
//getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
//if(i < weekday)
// $scope.days.push('');
//else
$scope.days.push(day++);
console.log($scope.days) ;
}
};
});
</script>
</body>
</html>

Related

Swapping data on ui-grid take a lot of time

I have one grid and according to some conditions, I have to change the data which comes from the back-end.The first time I load data from the back the grid works fine. When I start switching data the grid displays new data well but stays frozen for a while. I notice that this time is random and is often about 3 seconds or plus.
I tried to assign data to the grid through different ways but the result is the same:
1)
$scope.gridOptions = {
//some options,
data: $scope.myData
}
And then
Demande.query({lb: condition}, function (result) {
$timeout(function () {$scope.myData = result;},0);// I also try without $timeout
}
2) I try to assign the data directly to the grid
Demande.query({lb: condition}, function (result) {
$timeout(function () {$scope.gridOptions.data = result;},0);
}
3) I combine the above approachs with
a) $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ROW)
b) $scope.gridApi.core.refreshRows()
but the problem persists. I am using angular-ui-grid 4.0.1
Any idea will be appreciated.
Another option:
4) $scope.gridOptions.data = angular.copy($scope.myData);
Should give the grid the little time that it needs to breath!
Update:
angular.module('app', ['ui.grid'])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.gridOptions = {
columnDefs: []
}
for (var i = 0; i < 80; i++) {
$scope.gridOptions.columnDefs.push({
name: 'C' + (i + 1),
enableColumnMenu: false
});
}
var dataLoadCounter = 1;
$scope.switchData = function() {
$scope.gridOptions.data = [];
for (var i = 0; i < 1000; i++) {
$scope.gridOptions.data.push({});
for (var j = 0; j < 80; j++) {
$scope.gridOptions.data[i]['C' + (j + 1)] = 'D' + dataLoadCounter + (j + 1);
}
}
dataLoadCounter++;
}
$scope.switchData();
}]);
div[ui-grid] {
width: 4500px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.css" />
<div ng-app="app" ng-controller="MainCtrl">
<button ng-click="switchData()">Switch Data</button>
<div ui-grid="gridOptions">
</div>
</div>

How to create autogenerate ID in angular?

Want to create autogenerate code in angular inputbox on refresh page
like rand(function) in php. Im using this script for this. But problem
is its vanished on page refresh not working properly.
<script type="text/javascript">
function randString(x){
var s = "OL-";
while(s.length<x&&x>0){
var r = Math.random();
s+= (r<0.1?Math.floor(r*100):String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65)));
}
return s;
}
document.getElementById("referal_code").value = randString(10);
</script>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
Try this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getNewID() {
try {
var myDate = new Date();
var varID = myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
if (varID.Length > 15) {
varID = varID.substr(0, 15);
}
return varID;
} catch (e) {
console.log(e.message);
}
}
function randString(x){
var s = getNewID();
return s;
}
window.onload = function(){
document.getElementById("referal_code").value = randString(10);
}
</script>
</head>
<body>
<input required type='text' class='span2' id='referal_code' ng-model='empInfo.referal_code'>
</body>
</html>
For any attribute in angular world you can use interpolation like this:
<input id="{{randString(10)}}"/>
If you want to have a certain value as id and not get lost after refresh you have to save it on some web storage (localstorage, sessionstorage).
e.g. :
function randString(x){
// ... your function's logic
//Save it in localStorage before returning it
localStorage.inputId = s;
return s;
}
document.getElementById("referal_code").value = localStorage.inputId || randString(10)

Incrementally add date with ng-repeat

I have a variable $scope.date in my controller. In the view, I do ng-repeat over a couple of items. Each item has a duration in minutes. How would I go about to incrementally add time for every repeat and display this?
Add a function on the controller that calculates the date including the duration. Working code snippet:
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
$scope.someDate = new Date();
$scope.durations = [1, 2, 5, 6, 8];
$scope.calculateIncrementalDuration = function(index) {
var sum = 0;
for (var i = 0; i <= index; i++) {
sum += $scope.durations[i];
}
return sum;
}
$scope.calculateEndDate = function(startDate, index) {
return new Date(startDate.getTime() + $scope.calculateIncrementalDuration(index) * 60000);
}
});
.delay {
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
Start time: {{someDate.toUTCString()}}
<div class="delay" ng-repeat="duration in durations">Duration in minutes: {{calculateIncrementalDuration($index)}}
<div>End time: {{calculateEndDate(someDate, $index).toUTCString()}}</div>
</div>
</div>
I don't have the reputation for a comment, so please don't be angry at me, those who get angry at non-answers as answers, but I would highly recommend looking into moment.js for things like this.

bind nested ng-repeat to model

In the following example, I should ask for the name of six students. They will be grouped according to bedroom type.
2 -> double
1 -> single
3 -> tiple
So, it means that I'll have a array of students (6 students). I would like to get their names. I was trying to create a variable like 'count' and put as ng-model of the input and increment during the loop, but it didn't work.
full html:
<!doctype html>
<html ng-app="sampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller='SampleController'>
<div ng-repeat='i in numberOfAccommodations track by $index'>
Bedroom {{$index}}
<span ng-repeat='x in numberOfStudents[$index]'>
Student {{$index}}
<input type='text' ng-model='abroadStudents[???].name' /> <!-- this input to student model -->
</span>
</div>
<input type='button' value='test' ">
<script>
angular.module('sampleApp',[]).controller('SampleController',function($scope){
$scope.abroadStudents = new Array[6];
$scope.abroadAccommodation = new Array();
$scope.abroadAccommodation.push({ "bedroomType": 2}, { "bedroomType": 1 }, {"bedroomType": 3});
$scope.numberOfAccommodations = function()
{
var arr = new Array();
for (var i = 0 ; i < $scope.abroadAccommodation.length ; i++)
{
arr.push(i);
}
return arr;
}();
$scope.numberOfStudents = function()
{
var arr = new Array();
for (var x = 0 ; x < $scope.abroadAccommodation.length ; x++)
{
var temp = 0;
var intArr = new Array();
do
{
intArr.push(temp);
temp++;
}
while(temp < $scope.abroadAccommodation[x].bedroomType);
arr.push(intArr);
}
return arr;
}();
});
</script>
</body>
</html>
I rewrote your logic to create a more logical structure of objects which does not require relying upon the $index. It creates an Array of room objects, then iterates through the array of abroadAccommodation. For each abroadAccommodation, it adds a room, and based on type, adds the appropriate number of student objects. It is then very easy to use ng-repeat to iterate through each room to identify each student.
Note I also am using angular.forEach here.
<!doctype html>
<html ng-app="sampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller='SampleController'>
<div ng-repeat="room in rooms">
{{room.roomNum}}
<div ng-repeat="student in room.students">
{{student.bed}}
<input ng-model="student.name" />
</div>
</div>
Student List:
<div ng-repeat="room in rooms">
<div ng-repeat="student in room.students">
{{student.name}}
</div>
</div>
<script>
angular.module('sampleApp', []).controller('SampleController', function($scope) {
$scope.abroadAccommodation = new Array();
$scope.abroadAccommodation.push({
"bedroomType ": 2
}, {
"bedroomType ": 1
}, {
"bedroomType ": 3
});
$scope.rooms = function() {
var arr = [];
angular.forEach($scope.abroadAccommodation, function(type, count) {
var room = {
"roomNum": "room " + (count + 1),
students: []
};
angular.forEach(type, function(numBeds) {
for (i = 0; i < numBeds; i++) {
room.students.push({
"bed": "bed " + (i + 1),
"name": "student" + Math.random()
});
}
arr.push(room);
})
});
return arr;
}();
});
</script>
</body>
</html>
http://plnkr.co/edit/YaPo54NUBPk9AnZkGcCc?p=preview

Loop thru 100 background-images onClick

a) I have 100 body-background images
b) and a single link
The background image should change to the next one in the lot every time the link is clicked, going thru the lot one by one (would be nice if the name/number of current image also is displayed).
The images are all in a dedicated directory. jQuery is already loaded.
Anyone know where I can find the code to do this simply?
All the best...
var allImages = ["path/to/image2", "path/to/image1"];
$(document).ready(function() {
$("#theLink").click(function() {
var newImageLink = allImages.pop();
$("body").css("background-image", "url(" + newImageLink + ")");
});
});
You don't necessarily need to hard code the path to your images that way. You can name your images something like image_xxx.png, 1 - 100 and refer to that name in one place. That way if you ever need to change the name, you can easily do it in one place. Furthermore, make sure that the href attribute of the anchor tag is set to # to prevent page reloads on each click.
Here's a more complete solution that also does range checking and it wraps around when we reach our limit:
<script language="javascript" type="text/javascript">
<!--
var ctr = 0;
$(document).ready( function () {
nextBg();
});
function nextBg()
{
++ctr;
if( ctr <= 100 )
{
$("body").css( "background-image", "url(images/image_" + ctr + ".png)" );
$("#message").text("Current image: " + "image_" + ctr + ".png");
if( ctr == 100 )
ctr = 0;
}
}
//-->
</script>
</head>
<body>
<div>
<span id="message"></span><br />
<a href="#" onclick="nextBg();" />Next</a>
</div>
</body>
(added counter to gs' answer)
var allImages = ["path/to/image2", "path/to/image1"];
var counter = 0;
$(document).ready(function() {
$("#theLink").click(function() {
var newImageLink = allImages.pop();
$("body").css("background-image", "url(" + newImageLink + ")");
$("#displayhere").html("<b>"+ counter +"</b>");
counter = counter + 1;
});
});

Resources