Custom URL using Angular ngResource - angularjs

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>

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>

How to read value from json data and display in 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.

How to create the cross domain using angularjs?

Hi, I need to create a dropdown list which uses a cross domain to populate it. And i have set a url for it but couldn't find why it is not working .
When the url is in json format it works without any issues but the url is in a xml format. And this is my first work on API's so I will be thank full if anybody help me with this...
---index.html---
<!DOCTYPE html>
<html ng-app="App">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="script.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
li span.ng-binding {
color: #f00;
}
</style>
</head>
<body>
<div ng-controller="AppCtrl">
<h1>{{val}}</h1>
<select ng-options="p.ProductName for p in Product"></select>
</div>
</body>
</html>
---script.js---
var App = angular.module('App', [])
.controller('AppCtrl', function($scope, AppFact) {
$scope.val = "Testing the Page For CallsBacks";
AppFact.getData(function(Product) {
$scope.Product = Product;
});
})
.factory('AppFact', function($http) {
return {
getData: function(successcb) {
var url = 'http://xxxxxxxxx';
$http.jsonp(url).
success(function(Product, status, headers, config) {
//alert('ji');
console.warn(Product);
successcb(Product);
}).
error(function(Product, status, headers, config) {
//alert(Product);
//alert("Status is " + status);
});
}
};
});
And Here is my plunker:http://plnkr.co/edit/qq8sELDdZZB5QKe1Pj3T?p=preview
Plz guide me with this because i'm new to API's side..

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;
});

Angularjs getting data from controller scope to directive scope

I am trying to get data from resource then add it to isolate scope of directive but when i want to print it to screen i get error as undefined current_page here is the script
/**
* Created by yigit on 10.01.2014.
*/
var app = angular.module('kategori', [
'ngResource',
'apiBaseRoute'
]);
app.factory('Data', ['$resource', 'apiBaseRoute', function($resource, config){
return $resource(config.apiBasePath + 'kategori/?page=:page',{page:1},{
query:{
isArray: false,
method: 'GET'
}
});
}]);
app.controller('KategoriListCtrl',['$scope', 'Data', function($scope, Data){
$scope.allData = {data:null};
Data.query({}, function(data){
$scope.kategoriList = {data:data.cat.data};
$scope.allData.data = data.cat;
});
}]);
app.directive('paginate', function(){
return{
scope:{paginatorData: '=paginate'},
link: function(scope){
alert(scope.paginatorData.current_page);
}
}
});
<!DOCTYPE html>
<html ng-app="kategori">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="col-md-6 col-md-offset-3" ng-controller="KategoriListCtrl">
{{allData.current_page}}
<div paginate="allData"></div>
</div>
<script src="js/lib/angular.min.js"></script>
<script src="js/lib/angular-resource.js"></script>
<script src="js/kategori.js"></script>
<script src="js/apiroute.js"></script>
</body>
</html>
I read this article nested scope
But could not solve my problem.
So, the code alerts undefined. How can i solve this?
Can you show your HTML? You'll need to pass the property like this:
<div data-paginate="paginate"></div>

Resources