have a some data one my page that is in a ng-repeat.
When the page and data 1st loads the data shows up.
When I move away from the page (using Angular Routing) make a change to the data (gets saved in db) then come back into the page (make call to db get new data) the ng-repeat data does not refresh. I can see the new data loading into the array and it is the new data.
I start the process on the page with
var sp = this;
sp.viewData = [];
sp.employee = [];
sp.ViewDataTwo = [];
$(document).ready(function () {
var testHeader = setInterval(function () { myTimer() }, 1000);
function myTimer() {
if (addHeaderToken() != undefined) {
clearInterval(testHeader);
sp.usageText = "";
if (sessionStorage.getItem(tokenKey) != null) {
sp.associatedInfo = JSON.parse(getassociatedInfo());
loadDataOne();
loadDataTwo();
}
}
}
});
I do this because I need to get my security toke from a JS script that I have no power over changes. So I need to make sure the code has ran to get me the token.
here are the functions I call..
function loadPasses() {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
$http.get('/api/Employee/xxx', { params: { employeeId: sp.employeeId } }).then(function (data) {
sp.viewData = data.data;
for (var i = 0; i < $scope. viewData.length; i++) {
sp.passes[i].sortDateDisplay = (data.data.status == "Active" ? data.data.DateStart + "-" + data.data[i].DateEnd : data.data[i].visitDate);
sp.passes[i].sortDate = (data.data[i].status == "Active" ? data.data[i].DateStart: data.data[i].visitDate);
}
});
}
function loadDataTwo () {
$http.defaults.headers.common.Authorization = "Bearer " + addHeaderToken();
if (sessionStorage.getItem(tokenKey) != null) $http.get('/api/Employee',
{
params: { employeeId: sp.employeeId }
}).then(function (data) {
sp.employee = data.data;
var tempPassString = "";
sp.ViewDataTwo = [];
var totalA = 0;
var totalU = 0;
for (var p = 0; p < sp.employee.dataX.length; p++) {
sp.ViewDataTwo.push(sp.employee.dataX[p].description + "(" + /** math to update description **// + ")");
totalA += parseInt(parseInt(sp.employee.dataX[p].Anumber));
totalU += parseInt(sp.employee.dataX[p].Bnumber));
}
sp.usageArr.push(" Total: " + totalA- totalU) + "/" + totalA + " Available");
//$scope.$apply();
});
}
One my view sp.viewData and sp.ViewDataTwo are both in ng-repeats.
Works well on load.. when I go out and come back in. I see the data reloading. But the view does not.
I have hacked the Dom to get it to work for now. But I would like to do it the right way..
Any help.
I have used
$scope.$apply();
But it tells me the digest is already in process;
the views are in a template..
Please help
Related
I am opening multiple pages in an iframe (one by one) i.e. i want to do it synchronously. So in a for loop i want to set iframe src property to url1 then once this page is loaded move to url2 and so on..
<iframe id="iframeExportPDF" onload="test();"></iframe>
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
//alert(registrarIds[i].toString());
ganttPopup(urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString(), registrarIds[i]);
sleep(25000);
}
});
function ganttPopup(url, id) {
iframeExportPDF.src = url;
//window.open(url, "_blank", "ganttChartPopup_" + id.toString(), "width=1100,height=600,scrollbars=yes,resizable=yes");
}
P.S. Previously i was doing the same with opening multiple windows but since i have 1100 records, window.open would not be feasible.
I found my answer here
var urls = [], iCount;
$(function () {
$('#<%=Button1.ClientID%>').click(function (e) {
e.preventDefault();
var registrarIds = ($('#<%=lblRegistrarIdsForChart.ClientID%>').text()).split(',');
iCount = registrarIds.length;
for (var i = 0; i < registrarIds.length; i++) {
var link = window.location.href;
var urlBase = link.substring(0, link.lastIndexOf("/") + 1);
var url = urlBase + 'GPS/CompetencyAssessment/GanttChart.aspx?id=' + registrarIds[i].toString();
urls.push(url);
}
redirect_url();
});
function redirect_url() {
if (iCount >= 0) {
setTimeout(function () {
$('#iframeExportPDF').attr('src', urls[iCount]);
iCount--;
redirect_url();
}, 15000);
}
}
});
I have an Angular 1.3 application that has been upgraded to 1.6, and now a couple of functions dob't work.
These functions are called within a vanilla JS script that is called from within a controller, to forward onto another controller and view.
Here I my state:-
.state('track', {
url: '/:area /:trackId /:type',
parent: 'tracks',
component: 'trackDetails'
})
And here is my code within my vanilla JS script (which uses a third party library (a map) to render the actual view).
function getTrackLink(track) {
trackLink = "<div><a ui-sref=\"tracks/track({area:" + track.area + " + /trackId:"
+ track.id + "/type:" + track.type + " })\">" + track.name
+ "</a></div>";
console.log(trackLink);
return trackLink;
}
The links aren't clickable, and therefore won't navigate.The JS function is called within the controller, added below.....
function MapCtrl($rootScope, $http, $stateParams, SearchOp, SearchResultsService, $state) {
const vm = this;
console.log('MapCtrl called');
console.log("stateParams:"+$stateParams);
vm.results = null;
vm.loading = true;
let latitude = 0;
let longitude = 0;
let distance = 0;
let currentZoom = 7;
if ($stateParams && typeof ($stateParams.latitude) !== 'undefined') {
latitude = $stateParams.latitude;
longitude = $stateParams.longitude;
distance = $stateParams.distance;
SearchResultsService.set(latitude, longitude, distance);
$rootScope.searchPerformed = true;
} else if (!$rootScope.searchPerformed) {
console.log("Defaulting co-ordinates to user's home town");
latitude = $rootScope.currentLatitude;
longitude = $rootScope.currentLongitude;
distance = $rootScope.currentDistance;
SearchResultsService.set(latitude, longitude, distance);
$rootScope.searchPerformed = true;
} else {
console.log('Rendering last search results');
}
console.log(`Search Params: ${latitude} : ${longitude} : ${distance}`);
SearchResultsService.get().then(data => {
vm.loading = true;
console.log(`Retrieved data from service: ${data}`);
vm.results = data;
loadMap(vm.results, currentZoom, $state);
vm.loading = false;
}).catch(error => {
vm.loading = false;
vm.status = 'Unable to load trackdata: ' + error.message;
});
vm.search = (latitude, longitude, distance, currentZoom) => {
vm.loading = true;
SearchResultsService.set(latitude, longitude, distance);
SearchResultsService.get().then(data => {
console.log(`Retrieved data from service: ${data}`);
vm.results = data;
console.log("SearchResults"+ data);
loadMap(vm.results, currentZoom);
vm.loading = false;
}).catch(error => {
vm.loading = false;
vm.status = 'Unable to load trackdata: ' + error.message;
});
}
}
Any ideas appreciated.....
I don't see anywhere in the above code where the getTrackLink function is called from the controller. However as a solution, try adding:
$rootScope.apply()
Just after the getTrackLink function is called.
If the function is async, you can try wrapping the function call instead:
$rootScope.$apply(getTrackLink());
Probably, this is a problem with the sanitize. You have to trust your code. Do it carefully.
Have a look here: $sce
I think that you should use something like:
<div ng-bind-html="vm.something"></div>
In the controller
vm.something = $sce.trustAsHtml(vm.somethingUntrasted);
I am very new to AngularJS and currently I am working on a form which is designed in angularjs.
My task is to validate a textbox input with a list. If the value entered in textbox is not present in the list then it should throw a validation error.
I have written the below lines of code for getting the list items through rest API:
app.factory("EatonScanningFactory", ['$http', function($http) {
var EatonScanningFactoryObj = {};
EatonScanningFactoryObj.GetToolMaxTimeList = function (columnName) {
return $http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl
+ "/_api/web/lists/getbytitle('Tool%20Max%20Time')/Items/"
+ "?$select=Text,Value&$orderby=Text&$filter=Title eq '" + columnName + "'",
headers: { "Accept": "application/json;odata=verbose" }
});
}
It will return the list items into an array.
The below lines of code are for accessing calling the above function:
var getToolId = EatonScanningFactory.GetToolMaxTimeList('ToolNumber');
var getMaxLife = EatonScanningFactory.GetToolMaxTimeList('MaxLife');
I am unable to proceed further as I am not sure how to validate if my text box input is available in the list or not.
Please help
Hi there here is a plausible solution as an example:
$scope.list = EatonScanningFactory.GetToolMaxTimeList('MaxLife');
Javascript (Native) Example:
function validateList() {
var IsInList = false;
for (var i = 0; i < $scope.list.length; i++) {
if ($("#textbox").val() == $scope.list[i].listvalue) {
IsInList = true;
break;
}
}
return IsInList;
}
Angular Example:
$scope.validateFunction = function() {
angular.forEach($scope.list, function(value, key){
var IsInList = false;
if($("#textbox").val() == value.listvalue) {
IsInList = true;
break;
}
});
return IsInList;
}
//Invoke the function like follow:
$scope.validateFunction();
In my Service i have the vars i want to display and the getters for it:
var docsLoaded = 0;
var docsToLoad = null;
pouchService.getDocsLoaded = function () {
return docsLoaded;
};
pouchService.getDocsToLoad = function () {
return docsToLoad;
};
While the service is syncing, i want to count the synced docs
pouchService.syncNow = function () {
var foundLastSeq = false;
docsLoaded = 0;
docsToLoad = null;
remoteDB.info().then(function (remoteInfo) {
function findOutDiff(localPosition) {
docsToLoad = (remoteInfo.update_seq - localPosition) + 1;
console.log("docs to load: " + docsToLoad);
}
// start Sync progress
sync = localDB.sync(remoteDB, {live: false})
.on('change', function (info) {
console.log('AI change: ');
console.log(info);
if (info.direction === 'pull') {
if (foundLastSeq === false) {
foundLastSeq = true;
findOutDiff(info.change.last_seq);
}
}
console.log(docsLoaded + " from " + docsToLoad);
docsLoaded++;
})
In my HTML i want to display the progress like this:
{{pouchService.getDocsLoaded()}} from {{pouchService.getDocsToLoad()}}
Now i get sometimes a value from getDocsLoaded, but mostly its zero. When I cancel the Syncprogress i get the value where it's stopped.
So i get the value before it really starts and when it's over, but i want it during the sync progress. (on the console my my progressinfos are working as expected)
Any ideas?
The problem is in applying scope. Jim wrote a nice article about this problem:
jimhoskins.com/2012/12/17/angularjs-and-apply.html
Solved it:
$rootScope.$apply(function () {
docsLoaded++;
});
What I'm trying to do:
Update the status to "TAKEN" when the chat is closed.
Issue:
Can't get $scope.currentChat.$set() or $scope.currentChat.$update() to work when trying to update the status. (See the $scope.close() function.)
What I've tried:
Various methods including $set, $update; I don't know. A lot of things. Been researching this for several hours, and can't find a solution that works.
NOTES:
$scope.currentChat.$set({status:"TAKEN"}); Doesn't work.
$scope.currentChat.$getRecord('status'); Works. Returns:
Object {$value: "OPEN", $id: "status", $priority: null}
So what exactly is going on here? Why can't I seem to set the status to TAKEN?
The issue is currently in the $scope.close() function, when trying to update the status:
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
Here's my code:
bloop.controller('HomeCtrl', ['$scope', '$firebase', function($scope, $firebase) {
console.log("HomeController!");
var url = 'https://**********.firebaseio.com/tickets/';
var ref = new Firebase(url);
// $SCOPE.CREATETICKET
// - This function makes a connection to Firebase and creates the ticket.
$scope.createTicket = function() {
$scope.tickets = $firebase(ref).$asArray();
$scope.tickets.$add($scope.ticketObject).then(function(r) {
var id = r.name();
$scope.currentFBID = id;
$scope.syncTickets();
console.log("===========================");
console.log("CREATED TICKET: " + $scope.currentFBID);
console.log("URL: " + url + $scope.currentFBID);
console.log("===========================");
});
}
// $SCOPE.SYNCTICKETS
// - This function makes a connection to Firebase and syncs the ticket with the $scope to easily update the tickets.
$scope.syncTickets = function() {
var ticketRefURL = new Firebase(url + $scope.currentFBID);
$scope.currentChat = $firebase(ticketRefURL).$asArray();
$scope.currentChat.$save($scope.ticketObject);
var archiveRefURL = new Firebase(url + $scope.currentFBID + "/archive");
$scope.currentChat.archive = $firebase(archiveRefURL).$asArray();
console.log("===========================");
console.log("SAVED TICKET: " + $scope.currentFBID);
console.log("URL: " + ticketRefURL);
console.log("ARCHIVE URL: " + archiveRefURL);
console.log("===========================");
}
// $SCOPE.POST
// - This function pushes whatever is typed into the chat into the chat archive.
// - $scope.ticketObject.archive (is an array of objects)
$scope.post = function(name) {
// Push to ticketObject.archive array...
$scope.ticketObject.archive.push({
"name" : name,
"text" : $scope.chatText
});
// Logging the array to make sure it exists...
console.log("===========================");
console.log("CHAT ARCHIVE:");
console.log($scope.ticketObject.archive);
console.log("===========================");
$scope.currentChat.archive.$add({
"name" : name,
"text" : $scope.chatText
});
// This resets the text area so it's empty...
$scope.chatText = "";
} // WORKS
// $SCOPE.CLOSE
// - Closes the current ticket.
$scope.close = function() {
// $scope.ticketObject.status = "TAKEN";
// $scope.currentChat.$set({status:"TAKEN"});
console.log("===========================");
console.log("STATUS:");
console.log($scope.currentChat.$getRecord('status'));
console.log($scope.currentChat['status']);
console.log("===========================");
$scope.ticketObject = {};
$scope.ticket = false;
$scope.toggle();
}
// $SCOPE.TOGGLE
// - This function toggles the chat to be either open or closed.
$scope.toggle = function() {
if($scope.toggleState === false) {
$scope.toggleState = true;
$scope.checkTicket();
} else if($scope.toggleState === true) {
$scope.toggleState = false;
}
}
// $SCOPE.CHECKTICKET
// - This function checks to see if there's an existing ticket.
// - If there's not an existing ticket, it creates one.
$scope.checkTicket = function() {
if($scope.ticket === false) {
// Generate New Ticket Data
$scope.ticketObject = newTicket();
// Create the Ticket
$scope.createTicket();
// Ticket now exists.
$scope.ticket = true;
}
}
function newTicket() {
var ticketID = generateTicketID();
var newTicket = {
id: ticketID,
status: "OPEN",
name: "N/A",
email: "N/A",
date: generateDate(),
opID: "Unassigned",
opName: "Unassigned",
archive: [],
notes: []
}
return newTicket;
}
function generateTicketID() {
var chars = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var result = '';
for(var i=12; i>0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
function generateDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd;
}
if(mm < 10) {
dd = '0' + mm;
}
var date = mm + "/" + dd + "/" + yyyy;
return date;
}
}]);
$update and $set are part of the $firebase API. You are attempting to call them on the synchronized array returned by $asArray(), which is a $FirebaseArray instance. That has its own API, which includes neither update nor set.