I have a really long json that each comes from different schema.
I did push in order to get them all in one json - that works.
know I want to use a controller for all of them and display it to the screen.
my index
<!DOCTYPE html>
<html ng-app="showFrozen">
<head>
<title>frozen</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
</head>
<body ng-controller="showFrozenCtrl">
<tbody>
<div ng-repeat="themes in showFrozenController.themes" ng-show="$first">
<h2>{{themes.theme}}</h2>
<span>for age: </span>
<p>{{themes.age}}</p>
<span>description: </span>
<p>{{themes.description}}</p>
<p>{{themes.description_more}}</p>
<img ng-src="{{themes.image}}" width="170" height="170">
</div>
</table>
<script src="js/lib/angular/angular.min.js"></script>
<script src="js/showFrozenController.js"></script>
</body>
</html>
my controller
var showFrozen = angular.module('showFrozen',[]);
showFrozen.filter("allItems", function() {
return function(frozen) {
var resultArr = [];
angular.forEach(frozen,function(item) {
resultArr.push(item);
});
return resultArr;
};
});
var model = {};
showFrozen.run(function($http) {
$http.get("http://localhost:3000/frozen").success(function(data){
console.log(data);
model.frozen = data;
});
});
showFrozen.controller('showFrozenCtrl',function($scope) {
$scope.showFrozenController = model;
});
so I don't get any output - but I see the json in the console, I'm attaching an image.
In your controller model is undefined.
Move the HTTP call to your controller and in the success assign the scope.showFrozenController to data
You need to make your $http request inside of your controller.
showFrozen.controller('showFrozenCtrl',function($scope, $http) {
$http.get("http://localhost:3000/frozen").success(function(data){
console.log(data);
$scope.model = data;
});
});
This is because when you try and print items out in your template (html) what is actually being accessed inside of any {{ }} blocks is your $scope object. So to make data available to your template you must store it on your $scope.
Have a read of this blog post
showFrozen.factory('frozenDataSrv',function($http) {
return {
getFrozenData: getFrozenData
};
function getFrozenData() {
return $http.get("http://localhost:3000/frozen")
.then(getFrozenDataComplete)
.catch(getFrozenDataFailed);
function getFrozenDataComplete(response) {
return response.data.results;
}
function getFrozenDataFailed(error) {
logger.error('XHR Failed for getFrozenData.' + error.data);
}
}
});
showFrozen.controller('showFrozenCtrl',function($scope, frozenDataSrv) {
frozenDataSrv.getFrozenData()
.then(function(response){
console.log(response)
})
});
Related
So i've been using a test file to try and pull Shopify data from the store. What I THINK is the problem, is that the api is making the request to fetch the data, but it takes longer to fetch the data than to run through my script. So the variable gets set to null. I'm assuming I need a way to check if the promise is successful and/or write the data to a JSON file. Anyway, here's the code. The page shows up blank when you run it.
App.js
phonecatApp.controller('PhoneListController', function
PhoneListController($scope) {
var products_complete;
var products = [];
//init the client
const client = window.ShopifyBuy.buildClient({
domain: 'some-site.myshopify.com',
storefrontAccessToken: 'xxxxxxxxxxxx'
});
$scope.getShop = function () {
//get the complete product listings from shopify
client.product.fetchAll().then((raw_products) => {
products_complete = raw_products;
reduce_products();
$scope.products = $scope.setProductValue();
});
//reduce the products list down to necessary information
function reduce_products() {
for (var i in products_complete) {
var product_tmp = products_complete[i];
var product = {};
//add name and tags
product['title'] = product_tmp['title'];
product['tags'] = product_tmp['tags'];
product['type'] = product_tmp['productType'];
product['pic_urls'] = [];
//add the images
for (var j in product_tmp['images']) {
if (product_tmp['images'][j]['src'] != null) {
product['pic_urls'].push(product_tmp['images'][j]['src']);
}
}
product['vars'] = []
for (var k in product_tmp['variants']) {
var w = product_tmp['variants'][k]['weight'];
var p = product_tmp['variants'][k]['price'];
var a = product_tmp['variants'][k]['available'];
if (!((typeof w == 'undefined') && (typeof p == 'undefined') && (typeof a == 'undefined'))) {
product['vars'].push({
'weight': w,
'price': p,
'available': a
});
}
}
//add the current product to the final list
if (('title' in product) && ('tags' in product) &&
(product['pic_urls'].length != 0) &&
(product['vars'].length != 0)) {
products.push(product);
}
}
}
return products;
}
index.html
<!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title>Google Phone Gallery</title>
<link rel="stylesheet"
href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="app.css" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://sdks.shopifycdn.com/js-buy-sdk/v1/latest/index.umd.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src="bower_components/angular/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="PhoneListController" ng-cloak>
<ul>
<li ng-repeat="product in products">
<p>{{product.title}}</p>
</li>
</ul>
</body>
</html>
Your local variable products is not visible within your HTML. You should use $scope.products within _reduce_products_ function, or return the value and assign it to $scope.products.
The products var you are using in your HTML is $scope.products, that has the value of:
$scope.products = $scope.setProductValue();
So, in your promise success function you should update $scope.products with the products your are reducing in your _reduce_products_ function, or if you're using $scope.products for another thig, you should have another scope variable for that.
client.product.fetchAll().then((raw_products) => {
products_complete = raw_products;
// What's this? $scope.products = $scope.setProductValue();
$scope.products = reduce_products(); // return reduced products array
});
I have a problem where a page has two components but only one of them is fully rendered.
The problem seem to be related to $http. I have a angular project where I need to construct a page based on RESTful API. The pages are such that I can expect multiple requests for the same data. At the moment, the set of requests are not behaving correctly.
For the sake of the argument (and also because it is a use case), the following page makes the same request twice.
game.html:
<html ng-app="prvdApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>Providence</title>
<script src="/js/angular-1.6.2.js"></script>
<script src="/data-access/data-access.service.js"></script>
<script src="/score-info/score-info.component.js"></script>
<script src="/js/game.js"></script>
</head>
<body>
<div ng-controller="gameController">
<score-info game-id="8000"></score-info>
<score-info game-id="8000"></score-info>
</div>
</body>
game.js:
angular.module('prvdApp', [
'scoreInfo',
'drivesInfo' ]);
angular.
module('prvdApp').
controller('gameController', function() {
});
score-info.component.js:
angular.module('scoreInfo', [
'dataAccess'
]);
angular.
module('scoreInfo').
component('scoreInfo', {
templateUrl : '/score-info/score-info.template.html',
controller : function ScoreInfoController(dataAccess) {
self = this;
self.$onInit = function() {
dataAccess.game(self.gameId).then(function(game) {
self.game = game;
});
}
},
bindings : {
gameId : '<'
}
});
score-info.template.html:
<div>
Data available: {{ $ctrl.game != undefined }}
</div>
data-access.component.js:
angular.module('dataAccess', []);
angular.
module('dataAccess').
service('dataAccess',
function DataAccessService($http, $q) {
self = this;
self.game = function(game_id) {
var url = '/api/game/' + game_id;
return $http.get(url, { cache: true}).then(function(response) {
return response.data;
});
}
});
The behaviour is as follows:
The page renders with the content:
Data available: false
Data available: false
After some hundreds of milliseconds the $http -request finishes, the page is updated to the following state where only the latter component is updated.
Data available: false
Data available: true
It should be noted that the behaviour is the same even if the two components are of different types with different controllers, etc.
I make two directives .To communicate between two directives I used a factory .
but it not work properly ..I want to delete my text when I press delete button ..I take factory to do my task but it not working .I also try to take service .it also don't help
here is my code
http://plnkr.co/edit/Yenmira9J9XpjscQzRoX?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="app">
<a></a>
<b></b>
<script>
angular.module('app',[]).directive('a',function(){
return {
restrict :'E',
scope:{},
templateUrl:'a.html',
controller:'ts',
controllerAs:'vm'
}
}).controller('ts',function(sharedService){
var vm=this;
vm.delete=function(){
alert('--');
sharedService.deletepro();
}
}).directive('b',function(){
return {
restrict :'E',
scope:{},
templateUrl:'b.html',
controller:'bb',
controllerAs:'vm'
}
}).controller('bb',function(sharedService){
var pm=this;
pm.message= sharedService.sendData();
}).factory('sharedService', function() {
var data = {};
function deletepro(){
data = {};
}
function sendData(){
var obj = {name:"pQr"};
data = obj;
return data;
}
return {
sendData: sendData,
deletepro: deletepro
};
});
</script>
</body>
</html>
After your controller is first initialized, data and vm.message reference the same object, but when you run deletepro then data references a new object, but vm.message still references the old one.
If you want to pass data in this way, you must never replace data with a new object (otherwise, controllers will have to get the new object again).
Instead of data = {};, try data.name = '';
It looks like you're expecting that it will update because data is a shared reference. But you are resetting it to {}, which breaks the reference. You instead need to modify it:
function deletepro(){
for(var prop in data){
delete data[prop];
}
}
Also, keep in mind a and b are both real html tags, not sure if there are any issues ovewriting the standard ,
I know there are a few posts similar to this but I simply can't get any of them to work for me as intended. I'm trying to setup an event handler to listen to a location change on a specific scope. The code looks like this:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="verifyViewChange">
Test
</div>
<script>
var app = angular.module('myApp', []);
app.controller('verifyViewChange', function ($location, $scope) {
$scope.$on('$locationChangeStart', function (event) {
event.preventDefault();
alert("I'm preventing you from leaving the page");
});
});
</script>
</body>
</html>
When I load the page I get the warning, but not when clicking on the link. What do I need to do to make it work?
You should use the native 'beforeunload' event by adding it to the window.
Below is an example:
$scope.addUnloadEvent = function(){
if (window.addEventListener) {
window.addEventListener("beforeunload", handleUnloadEvent);
} else {
//For IE browsers
window.attachEvent("onbeforeunload", handleUnloadEvent);
}
}
function handleUnloadEvent(event) {
event.returnValue = "Your warning text";
};
//Call this when you want to remove the event, example, if users fills necessary info
$scope.removeUnloadEvent = function(){
if (window.removeEventListener) {
window.removeEventListener("beforeunload", handleUnloadEvent);
} else {
window.detachEvent("onbeforeunload", handleUnloadEvent);
}
}
//You could add the event when validating a form, for example
$scope.validateForm = function(){
if($scope.yourform.$invalid){
$scope.addUnloadEvent();
return;
}
else{
$scope.removeUnloadEvent();
}
}
The [fix above] is great just added this bit to the handleUnloadEvent...
function handleUnloadEvent(event) {
/*
This bit here theres another bind that says if this fields initial value is
not the same as its current value add the class of input-changed if it is
remove the class...so you can flag any page ya want to prompt a dialog based
on presence of a class on an input.
*/
var changeCheckCount = $('.input-changed').length;
console.log('changeCheckCount',changeCheckCount);
if(changeCheckCount === 0)
{
$scope.removeUnloadEvent();
}
else if(changeCheckCount > 0)
{
event.returnValue = "You have Unsaved changes do you really want to leave?";
}
Allows you to say if you want dialog to reload or leave page with just a class...Suppose you could bind the dialog too by finding the first one with .input-changed and have a data attribute on it with the message to show as the dialog.
Below is working example , it may helpful to you:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="myApp" ng-controller="verifyViewChange">
Test
</div>
<script>
var app = angular.module('myApp', []);
app.controller('verifyViewChange', function ($location, $scope) {
$scope.funConfirm = function () {
var retVal = confirm("I'm preventing you from leaving the page");
if (retVal == true) {
return false;
} else {
event.preventDefault();
return false;
}
}
});
</script>
var msg = document.getElementById('inputXML').innerHTML;How to pass input xml as a parameter to web service and displaying response from web service using angular javascript in html.
Here is my code, please help, i m not able to get reponse from web service.
<div ng-app="customerApp" ng-controller="customersController">
<ul>
HI<br><br><li ng-repeat="x in names">{{x}}</li>
</ul>
</div>
<script>
var app = angular.module('customerApp');
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
function customersController($scope, $http, setAsXMLPost) {
var msg = document.getElementById('inputXML').innerHTML;
$http.post("url.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}
</script>
<div id="inputXML">
<ACORD> <SignonRq> <UserId>CUser</UserId> <Password>XuViDgegi/KtGyJuXfuMrw==</Password>
<SignonPswd> <CustId> < </ACORD>
</div>
Because you are not retriving the content of the div. You are simply extracting #inputXML node from the DOM tree. You can try is
var msg = document.getElementById('inputXML').innerHTML;
I am not sure about xml but you are not posting it, use innerHTML to get actual xml from <div id="inputXML">.
inputXML : msg.innerHTML // use innerHTML to get the actual xml
Have you checked if your controller is executing correctly, I think the standard controller declaration would be something like this:
.controller('customersController', ['$scope', '$http', 'setAsXMLPost',function($scope, $http, setAsXMLPost){
var msg = document.getElementById('inputXML').innerHTML;
$http.post("http://nordevd208wa1x.csc-fsg.com/TPOServiceEnh7/TPOService/TPOService.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
$scope.names = response;
});
}]);
in var msg you are getting a javascript object though you need complete html to process so it should be
var = document.getElementById('inputXML').innerHTML;
Also default tranformRequest of $http in angular js is json you will have to change it to text/xml i wrote an article on how you could change it tranformRequest example angularjs
complete example, filename is test.php placed at root
<?php
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
$xmlData = file_get_contents('php://input');
header("Content-type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>' . $xmlData;
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body >
<title>Simple xml post in angularjs Web Application</title>
<meta name="Description" content="Simple xml post in angularjs Web Application">
<div ng-app="customerApp" ng-controller="customersController">
<ul>
<li ng-repeat="x in users">{{x}}</li>
</ul>
</div>
<div id="inputXML">
<ACORD>
<SignonRq><UserId>CUser1</UserId><Password>XuViDgegi/KtGyJuXfuMrw==</Password></SignonRq>
<SignonRq><UserId>CUser2</UserId><Password>XuViDgegi/KtGyJuXfuMrw==1</Password></SignonRq>
</ACORD>
</div> <!-- Libraries -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var app = angular.module('customerApp', []);
app.factory(
"setAsXMLPost",
function() {
//prepare the request data for the form post.
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformRequest);
}
);
app.factory(
"getAsXML",
function() {
//prepare the request data for the form post.
function transformResponse(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "text/xml; charset=utf-8";
// using parsexml for xml
return(jQuery.parseXML(data));
}
return(transformResponse);
}
);
function customersController($scope, $http, setAsXMLPost, getAsXML) {
var msg = document.getElementById('inputXML').innerHTML;
$scope.users = [];
$http.post("test.php", msg, {transformRequest: setAsXMLPost, transformResponse: getAsXML}).success(function(returnedXMLResponse) {
//here you will get xml object in reponse in returnedXMLResponse
});
}
</script>
</body>
</html>