I am newbie to AngularJs. Here is my code. In this i am trying to build the url by getting system date. But the values are not substituting at the time of jsonp request. I don't know Why.
Here when i try to add parameters manually. i am getting the values. But when i try to use the variables i am not getting the output.
$scope.getCurrentMonthData = function(){
$scope.date = new Date();
$scope.startday = 1;
$scope.currentday = $scope.date.getDate()+1;
$scope.month = $scope.date.getMonth()+1;
$scope.year = $scope.date.getFullYear();
$scope.start= $scope.year+'/'+$scope.month+'/'+$scope.startday;
$scope.end = $scope.year+'/'+$scope.month+'/'+$scope.currentday;
$scope.url1 = $rootScope.ApiWeatherHost+'/climo/v1/actuals/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
$scope.url2 = $rootScope.ApiWeatherHost+'/climo/v1/records/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
$scope.url3 = $rootScope.ApiWeatherHost+'/climo/v1/normals/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
$http.jsonp($scope.url1).then(function(msg){
console.log(msg.data);
});
$http.jsonp($scope.url2).then(function(msg){
console.log(msg.data);
});
$http.jsonp($scope.url3).then(function(msg){
console.log(msg.data);
});
};
I don't see where you are defining location_key so I don't know for certain if that is your problem, but when I run the following code, I see all three URL's created.
Have you checked to see if there is an error when you attempt to make those requests?
(function($scope, $rootScope){
$scope.date = new Date();
$scope.startday = 1;
$scope.currentday = $scope.date.getDate()+1;
$scope.month = $scope.date.getMonth()+1;
$scope.year = $scope.date.getFullYear();
$scope.start= $scope.year+'/'+$scope.month+'/'+$scope.startday;
$scope.end = $scope.year+'/'+$scope.month+'/'+$scope.currentday;
$scope.url1 = $rootScope.ApiWeatherHost+'/climo/v1/actuals/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
$scope.url2 = $rootScope.ApiWeatherHost+'/climo/v1/records/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
$scope.url3 = $rootScope.ApiWeatherHost+'/climo/v1/normals/'+$scope.location_key+'.json?start='+$scope.start+'&end='+$scope.end+'&apikey='+$rootScope.ApiKey;
var output = $('#output');
$('<div>').text($scope.url1).appendTo(output);
$('<div>').text($scope.url2).appendTo(output);
$('<div>').text($scope.url3).appendTo(output);
}({}, {ApiWeatherHost:'www.fake-api.com', ApiKey:'12345'}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='output'></div>
Related
How can I get the specific date month coming from the backend on angularJS
I wish to add something like this:
var curMonth = new Date().getMonth();
var monthData = vm.paymentsData[0].date.Date().getMonth();
if (curMonth == monthData) {
console.log ("Same Month");
}
Im getting error on:
var monthData = vm.paymentsData[0].date.Date().getMonth();
it says:
angular.js:14328 TypeError: vm.paymentsData[0].date.Date is not a function
Thanks
Data from the backend
I think your code should be written as follows:
var curMonth = new Date().getMonth();
// this maybe a string .. and you cannot call Date() function in that way.
var monthData = vm.paymentsData[0].date;
// Date function should be called this way.
var monData = (new Date(monthData)).getMonth();
if (curMonth == monData) {
console.log ("Same Month");
}
I'm using angularjs 1.5.8 to basically mimic an excel table with equations. THere are three rows requiring two inputs that affect two outputs. I'm struggling on how to write my script to include multiple controllers as I'm building a controller for each row. If I comment out the second and third controller in my script, the first row works just fine. When no lines are commented, nothing works. I feel like I'm very close but not sure where I'm going wrong. Any help would be appreciated.
Here is the working controller:
angular.module('ADMApp', [])
.controller('ADMFarViewController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADMFarViewImgHeightvar = Number(ctrl.ADMFarViewImgHeightvar || 0);
var ADMFarViewVertPixvar = Number(ctrl.ADMFarViewVertPixvar || 0);
ctrl.ADM_FarViewFarthestViewer_ans = (ADMFarViewImgHeightvar * 3438) / ADMFarViewVertPixvar;
ctrl.ADM_FarViewViewRat_ans = ctrl.ADM_FarViewFarthestViewer_ans / ADMFarViewImgHeightvar;
}
}]);
Here is my plunker: https://plnkr.co/edit/6nKEPCeOqx7zEFx5M5WZ
Don't redefine your module every time.
// Code goes here
var ADMApp = angular.module('ADMApp', []);
ADMApp.controller('ADMFarViewController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADMFarViewImgHeightvar = Number(ctrl.ADMFarViewImgHeightvar || 0);
var ADMFarViewVertPixvar = Number(ctrl.ADMFarViewVertPixvar || 0);
ctrl.ADM_FarViewFarthestViewer_ans = (ADMFarViewImgHeightvar * 3438) / ADMFarViewVertPixvar;
ctrl.ADM_FarViewViewRat_ans = ctrl.ADM_FarViewFarthestViewer_ans / ADMFarViewImgHeightvar;
}
}]);
ADMApp.controller('ADMMinImgController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADM_MinImgHeightVertPix_var = Number(ctrl.ADM_MinImgHeightVertPix_var || 0);
var ADM_MinImgHeightFarthestViewer_var = Number(ctrl.ADM_MinImgHeightFarthestViewer_var || 0);
ctrl.ADM_MinImgHeightImageHeight_ans = (ADM_MinImgHeightVertPix_var * ADM_MinImgHeightFarthestViewer_var) / 3438;
ctrl.ADM_MinImgHeightViewRat_ans = ADM_MinImgHeightFarthestViewer_var / ctrl.ADM_MinImgHeightImageHeight_ans;
}
}]);
ADMApp.controller('ADMMaxImgController', [function() {
var ctrl = this;
ctrl.ADMCalc = function() {
var ADM_MaxImgImageHeight_var = Number(ctrl.ADM_MaxImgImageHeight_var || 0);
var ADM_MaxImgFarthestViewer_var = Number(ctrl.ADM_MaxImgFarthestViewer_var || 0);
ctrl.ADM_MaxImgVertPix_ans = (ADM_MaxImgImageHeight_var * 3438) / ADM_MaxImgFarthestViewer_var;
ctrl.ADM_MaxImgViewRat_ans = ADM_MaxImgFarthestViewer_var / ADM_MaxImgImageHeight_var;
}
}]);
angular.module('ADMApp', [])
That line of code defines the module 'ADMApp'. Since you hve this line three times in your code, you define the same module thrice, effectively overwriting its previous definition, containing the previously added controller.
Save it in a variable, or use angular.module('ADMApp')to get a reference to the previously defined module.
I have an iframe inside an angularjs application. I am switching to the iframe using switchTo().
I need to get the table first which has the value I'm looking for. I need to get the Yield total from within the table. I need to find the yieldtotal inside the table using cssContainingText() beacuse the attributes for everything inside the table are the same. The yield total may or may not be present. I used yieldTotal.isPresent() but it throws an error saying "window.angular is undefined. It may be because it is not an angular application"
I cannot use browser.driver.findElement because I cannot find elementbytext that way.
function verifyGrossInvoiceTotal(){
browser.ignoreSynchronization = true;
browser.driver.switchTo().frame('viewDocumentInFrame');
var ProductTable = $('table.invoice-details'));
var sum = 0;
var YieldTotal = ProductTable .element(by.cssContainingText('td', 'Yield Total')).element(by.xpath('..'));
**YieldTotal.isPresent()**.then(function (isPresent){
if(isPresent){
var totalAmount = YieldTotal .$$('td').get(3);
totalAmount.getText().then(function (text) {
text = parseFloat(text.replace(/[^0-9.]/g, '')).toFixed(2);
sum = parseFloat(sum) + parseFloat(text);
});
}
});
});
I think this is because td is not directly under ProductTable. Can you try something like below? Basically 'table.invoice-details td' CSS means, find any td anywhere under table.invoice-details
function verifyGrossInvoiceTotal(){
browser.ignoreSynchronization = true;
browser.driver.switchTo().frame('viewDocumentInFrame');
var sum = 0;
var YieldTotal = element(by.cssContainingText('table.invoice-details td', 'Yield Total'));
YieldTotal.isPresent().then(function (isPresent){
if(isPresent){
var totalAmount = YieldTotal .$$('td').get(3);
totalAmount.getText().then(function (text) {
text = parseFloat(text.replace(/[^0-9.]/g, '')).toFixed(2);
sum = parseFloat(sum) + parseFloat(text);
});
}
});
});
I've got a factory that gets my data from Firebase, and I want my controller to be able to access it. However, when I console.log the data in my controller, it isn't the Array[10] that I would expect it to be, but rather an Array with keys 0,1,2,..10, $$added, $$error, $$moved,... and so on. However, when I skip out on using the factory, and use $asArray() method on my firebase ref directly in my controller it shows up nicely as an Array[10]
In my factory, this is what it looks like..
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
factory.getProducts = function(){
return products;
};
Controller
$scope.products = marketFactory.getProducts();
console.log($scope.products) in my controller should be Array[10], but instead it's an Array with the data + a lot more $$ methods. Anyone know what's going on? Thanks
EDIT: Full Factory File
(function(){
var marketFactory = function($firebase){
var listingsref = new Firebase("https://something.firebaseio.com");
var sync2 = $firebase(listingsref);
var products = sync2.$asArray();
var factory = {};
factory.getProducts = function(){
console.log(products);
return products;
};
factory.getProduct = function(productId){
for(var x = 0; x<products.length ;x++){
if(productId == products[x].id){
return {
product:products[x],
dataPlace:x
};
}
}
return {};
};
factory.getNextProduct = function(productId, e){
var currentProductPlace = factory.getProduct(productId).dataPlace;
if (e=="next" && currentProductPlace<products.length){
return products[currentProductPlace+1];
}
else if(e=="prev" && currentProductPlace>0){
return products[currentProductPlace-1];
}
else{
return {};
}
};
factory.componentToHex = function(c){
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
};
factory.rgbToHex = function(r,g,b){
return "#" + factory.componentToHex(r) + factory.componentToHex(g) + factory.componentToHex(b);
};
factory.hexToRgb = function(hex) {
if(hex.charAt(0)==="#"){
hex = hex.substr(1);
}
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + ", " + g + ", " + b;
};
factory.parseRgb = function(rgb){
rgb = rgb.replace(/\s/g, '');
var red = parseInt(rgb.split(',')[0]);
var green = parseInt(rgb.split(',')[1]);
var blue = parseInt(rgb.split(',')[2]);
return {
r:red,
g:green,
b:blue
};
};
return factory;
};
marketFactory.$inject = ['$firebase'];
angular.module('marketApp').factory('marketFactory', marketFactory);
}());
This snippet gets a synchronized AngulareFire array of products:
var products = sync2.$asArray();
The AngularFire documentation is a bit off on this point: what you get back from $asArray() is not an array, but the promise of an array. At some point in the future your products variable will contain an array. This is done because it may take (quite) some time for your array data to be downloaded from Firebase. Instead of blocking your code/browser while the data is downloading, it returns a wrapper object (called a promise) and just continues.
Such a promise is good enough for AngularJS: if you simply bind products to the scope and ng-repeat over it, your view will show all products just fine. This is because AngularFire behind the scenes lets AngularJS know when the data is available and Angular then redraws the view.
But you said:
console.log($scope.products) in my controller should be Array[10]
That is where you're mistaken. While AngularFire ensures that its $asArray() promise works fine with AngularJS, it doesn't do the same for console.log. So your console.log code runs before the data has been downloaded from Firebase.
If you really must log the products, you should wait until the promise is resolved. You this this with the following construct:
products.$loaded().then(function(products) {
console.log(products);
});
When you code it like this snippet, the data for your products will have been downloaded by the time console.log runs.
Note that the object will still have extra helper methods on it, such as $add. That is normal and also valid on an array. See the documentation for FirebaseArray for more information on what the methods are, what they're for an how to use them.
So I edited the code in the plnkr at http://plnkr.co/M4PqojtgRhDqU475NoRY.
The main differences are the following:
// Add $FirebaseArray so we can extend the factory
var marketFactory = function($firebase, $FirebaseArray){
var listingsref = new Firebase("https://something.firebaseio.com");
// Actually extend the AngularFire factory and return the array
var MarketFactory = $FirebaseArray.$extendFactory(factory);
return function() {
var sync = $firebase(listingsref, {arrayFactory: factory});
return sync.$asArray();
};
Check out https://www.firebase.com/docs/web/libraries/angular/guide.html#section-extending-factories for more information on extending AngularFire entries. You will likely need to make some adjustments to the rest of the factory code.
Even though I have my userscript restricted to one domain, any site I visit that uses Jquery experiences all kinds of nasty issues when my script is active. Checking the error console in chrome reveals an identical error on all sites:
"Uncaught TypeError: Property '$' of object [object Window]"
What's causing this? My objective is to get my userscript running in noconflict mode on a site that uses both jquery and prototype. I didn't make the code above var = myFunction, so I don't know what about it is causing the problem I'm running into. Any suggestions?
// ==UserScript==
// #name Restore Dashboard Tags
// #namespace http://userstyles.org
// #description This script restores a user's tracked tag list to the sidebar on tumblr
// #author
// #homepage
// #history 1.0 first version
// #include http://www.tumblr.com/*
// #match http://www.tumblr.com/*
// ==/UserScript==
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = Window;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
var myFunction = function() {
jQuery('div#right_column ul:first-child').after('<ul class="controls_section" id="tracked_tags"></ul>');
jQuery('div.tracked_tags a').each(function (i) {
var tagID = jQuery(this).attr("id");
var tagIDNumber = tagID.replace('tag_','');
var tagName = jQuery(this).attr("href");
var tagNameClean = tagName.replace('/tagged/','');
var tagContent ='';
tagContent += '<li><a href="'+tagName+'" id="'+tagID+'" class="tag">';
tagContent += '<div class="hide_overflow">'+tagNameClean+'</div>';
tagContent += '<span id="tag_unread_'+tagIDNumber+'" class="count" style=""></span></a></li>';
jQuery(tagContent).appendTo('div#right_column ul#tracked_tags');
});
};
var NewPosts = function(){
jQuery('div.tracked_tags > div').each(function (i) {
var thisIndex = jQuery(this).index();
if (jQuery(this).find('small').length){
var postCount = jQuery(this).find('small').text();
jQuery('div#right_column ul#tracked_tags li:eq('+thisIndex+')').find('.count').html(postCount.replace("new posts", "") );
}
});
setTimeout(NewPosts,30000);
}
addJQuery(myFunction);
addJQuery(NewPosts);
The problem has been solved! Someone on another site IDed the culprit as jQuery = $ = p.jQuery.noConflict();; since I wasn't loading my own copy of Jquery I didn't need noConflict, and its usage was hiding Jquery from the rest of the page.