How to read value from json data and display in angularjs - angularjs

I want to display name in string format but Main.html page is not reading value from session.json page.so please help me
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope, Session) {
$scope.name = 'World';
$scope.session = Session;
});
app.run(function(Session) {}); //bootstrap session;
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json')
.then(function(r) { return Session.data = r.data;})
}
};
Session.updateSession();
return Session;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Hello {{name}}</h1>
Welcome,
<pre ng-bind='session.data.username | json'></pre>
</body>
</html>
This is session.json page but in $http.get('session.json') it is not reading value from this page .
{ "username": "John Smith" }
how to read string from the json page to main.html and display

See the following code,
$http({
"method": "get",
"url": "session.json"
});
Here session.json and this file( the file in which this $http call is present) are in the same folder.

Related

Error while using get request in AngilarJS

I have some JSON data in stored in file: weeklyData.json (which is inside folder json) that I want to display in console using GET request, but I'm getting result undefined.
My app.js file consist both approaches for GET request but the result remains same: undefined.
HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crazy Data Component</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>{{msg}}</h1>
<script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
<script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="js/app.js"></script>
<!-- <script src=""></script>-->
</body>
</html>
app.js
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.msg = "Something";
$http({
method: 'GET',
url: 'json/weeklyData.json',
headers: {
'Content-type': 'application/json'
}
}).then(function (response) {
console.log(response.data)
}, function (error) {
console.log(error.data)
})
})
// $http.get('json/weeklyData.json').success(function (data) {
// $scope.dub = data;
// console.log('$scope.dub', $scope.dub);
// })
//})
Can someone suggest something?
Your code is working.. check below snippet,
Your sample json is not accessed. check your url .
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.msg = "Something";
$http({
method: 'GET',
url: 'https://www.w3schools.com/angular/customers.php',
headers: {
'Content-type': 'application/json'
}
}).then(function (response) {
console.log(response.data)
}, function (error) {
console.log(error.data)
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crazy Data Component</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>{{msg}}</h1>
<script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
<script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="js/app.js"></script>
<!-- <script src=""></script>-->
</body>
</html>

Is it possible to inject factory into service in AngularJs?

I have created some function in factory
App.factory('CustomHttpRequest', function ($http, $q) {
return {
ajaxRequest: function () {
return "test";
}
}
});
and I want to Access it in service like below
hhwtApp.service('listPlacesService', ['$rootScope', 'CustomHttpRequest', function($rootScope, CustomHttpRequest) {
this.listPlacesData = function () {
CustomHttpRequest.ajaxRequest();
}
}]);
yes you can use like below,your almost close......
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,listPlacesService) {
$scope.name = 'World';
$scope.checking =listPlacesService.listPlacesData();
console.log($scope.checking);
});
app.service('listPlacesService', [ 'CustomHttpRequest', function( CustomHttpRequest) {
this.listPlacesData = function () {
return CustomHttpRequest.ajaxRequest();
}
}]);
app.factory('CustomHttpRequest', function () {
return {
ajaxRequest: function () {
return "test";
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{checking}} done!</p>
</body>
</html>
check the console which will return "test" to your controller
You already have it injected. Make sure the modules are connected.

Custom URL using Angular ngResource

I would like to know the best practice for connecting with my API as it works as following:
GET -> products/list/latest -> return list of latest products
GET -> products/list/popular -> return list of popular products
GET -> products/list/trending -> return list of trending products
and then when I want a detail of the each product, it is just:
GET -> products/:id
I got the following code in my services.js:
.factory('ProductService', function ($resource) {
return $resource('http://domainname.com/api/products/:product',{product: "#product"});
})
But I really don't know how to access these custom URLs. Can I use the ngResource for that?
Thanks!
Please see here https://docs.angularjs.org/api/ngResource/service/$resource
you can add custom action to ngResources
ie:
var app = angular.module('app', ['ngResource']);
app.factory('ProductService', function($resource) {
var actions = {
'latest': {
method: 'GET',
url: 'api/products/latest '
},
'popular': {
method: 'GET',
url: 'api/products/popular'
},
'trending': {
method: 'GET',
url: 'api/products/trending '
}
};
var ProductService = $resource('/api/products/:productId', {ProductId: '#id'}, actions);
return ProductService;
});
app.controller('MainCtrl', function($scope, ProductService) {
$scope.name = 'World';
ProductService.latest();
ProductService.popular();
ProductService.trending();
ProductService.query();
ProductService.get({id: 1});
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-resource.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>

Angular JS - Controller Undefined

I am a newbie to the AngularJS World. I have this example to define a controller for AngularJS page. I ended up displaying the raw text in the browser when tried to open the page.
I am trying with downloading the angular.js (lib/angular.js) to local filesystem.
The page is as given below:
<!doctype html>
<html ng-app>
<head>
<script src="lib/angular.js"></script>
<script type="text/javascript">
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
</script>
</head>
<body>
<div ng-controller="MyController">
<h1>Hello {{clock}}!</h1>
</div>
</body>
</html>
I ended up getting the result as below:
Hello {{clock}}!
In the browser console, I am getting the error log as follows:
Error: [ng:areq] Argument 'MyController' is not a function, got undefined
What am I missing?
Best Regards,
Chandra.
You need to initiate an angular module and create a controller using the same.
For Example:
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
});
And then you need to specify the app in the html markup with ng-app="myApp"
So your html will be:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyController">
<h1>Hello {{clock}}!</h1>
</div>
</body>
</html>
Working Plunkr

AngularJS - controllers communication

On my site I have the following structure
Header_controller:
myApp.controller('Header_controller',function($scope,$rootScope,$location,Genral_model){
$scope.logout = function(){
var data = {};
$rootScope.$emit('logout_clicked', data); // NOT WORKING
$rootScope.$broadcast('logout_clicked', data); // NOT WORKING
}
});
Users_controller:
myApp.controller('Users_controller', function ($scope,$rootScope,Users_model,$location,$state) {
$rootScope.$on('logout_clicked', function(event, resp) {
Users_model.unRegisterCookies();
});
})
Users_model:
myApp.factory('Users_model', function($rootScope,$http,$cookies) {
var factory={};
factory.unRegisterCookies = function(){
alert('log out');
}
return factory;
});
I'm trying to invoke unRegisterCookies function by sending broadcast from Header_controller to Users_controller, but it's doesn't work with emit and not with broadcast.
How to make it work?
This is the same basic code you're trying and it's working for me. Maybe there's an error somewhere else in your code?
http://plnkr.co/edit/SADWwkZWztoVJVjv0tKt
html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.0.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="HeaderCtrl">
<p>Button has been hit {{counter}} times.</p>
</div>
<div ng-controller="UsersCtrl">
<button ng-click="pushme()">Count Me In</button>
</div>
</body>
</html>
script:
var app = angular.module('plunker', []);
app.controller('HeaderCtrl', function($scope, $rootScope) {
$scope.counter = 0;
$rootScope.$on('countMeIn', function (event, data) {
$scope.counter = $scope.counter + 1;
});
});
app.controller('UsersCtrl', function($scope, $rootScope) {
$scope.pushme = function() {
$rootScope.$emit("countMeIn", {});
};
});
See this plnkr for working version of your code:
http://plnkr.co/edit/JN5yWBUjmjBh5m7FiQww
This is pretty identical to the code you posted and it's working. You might have some other error in your page. If you are in Chrome or FireFox, pull up the console and see what errors are being shown for your page.
html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.0.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script data-require="angular.js#1.0.x" src="https://code.angularjs.org/1.2.28/angular-cookies.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="HeaderCtrl">
<h1>Headers Controller</h1>
<button ng-click="logout()">Log out</button>
</div>
<div ng-controller="UsersCtrl">
<h1>Users Controller</h1>
</div>
</body>
</html>
script:
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('HeaderCtrl', function($scope, $rootScope) {
$scope.logout = function(){
var data = {};
$rootScope.$emit('logout_clicked', data); // NOT WORKING
$rootScope.$broadcast('logout_clicked', data); // NOT WORKING
}
});
myApp.controller('UsersCtrl', function($scope, $rootScope, Users_model) {
$rootScope.$on('logout_clicked', function(event, resp) {
Users_model.unRegisterCookies();
});
});
myApp.factory('Users_model', function($rootScope,$http,$cookies) {
var factory={};
factory.unRegisterCookies = function(){
alert('log out');
}
return factory;
});

Resources