for example I want to view data from two urls:
1- http://jsonplaceholder.typicode.com/posts/
2- http://jsonplaceholder.typicode.com/todos/
Can I load data from these two url's in one app with two controllers in one view page?
Use $http.get to issue the query (JSFiddle):
angular.module('Joy', [])
.controller('CtrlOne', ['$http', '$scope', function ($http, $scope) {
$http.get('http://jsonplaceholder.typicode.com/posts/').then(function (data) {
$scope.posts = data.data;
});
}])
.controller('CtrlTwo', ['$http', '$scope', function ($http, $scope) {
$http.get('http://jsonplaceholder.typicode.com/todos/').then(function (data) {
$scope.todos = data.data;
});
}]);
HTML:
<div ng-app="Joy">
<div ng-controller="CtrlOne">{{ posts[0] | json }}</div>
<div ng-controller="CtrlTwo">{{ todos[0] | json }}</div>
</div>
Related
I am using angular routers
app.config(function($routeProvider) {
$routeProvider
.when('/comment/list', {
templateUrl: 'commentList.htm',
controller: 'mainController'
})
});
<td ng-show="btnUADetails" ng-click="loadPage('commentList', x.userName);">
<a class="detailButton" href="#/comment/list"></a>
</td>
and here is my angular function
$scope.loadPage = function(pageId, id) {
if (pageId == "commentList") {
$scope.getServerData($scope.generateUrl(pageId, 'json', id)).then(function(result) {
$scope.serverComment = result;
});
} else {
//do something
}
}
Before $HTTP returns response html page loads and i am getting clean data in html table . Can i load this page after my functions returns result ? Or load html file first and load it again when functions returns result ?
When the router changes routes, it destroys the $scope of the current view and creates a new $scope with a new instance of the controller.
Include any information the new view needs as query parameters in the new URL.
Change the link to include a parameter:
<td ng-show="btnUADetails" ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶l̶o̶a̶d̶P̶a̶g̶e̶(̶'̶c̶o̶m̶m̶e̶n̶t̶L̶i̶s̶t̶'̶,̶ ̶x̶.̶u̶s̶e̶r̶N̶a̶m̶e̶)̶;̶"̶ >
<a class="detailButton" href="#/comment/list?id={{x.userName}}"></a>
</td>
Use the parameter in the controller:
app.controller("mainController", function($scope, $route) {
this.$onInit = function() {
if ($route.current.templateUrl == 'commentList.htm') {
var pageId = 'comment';
var id = $route.current.params.id;
$scope.getServerData($scope.generateUrl(pageId, 'json', id))
.then(function(result) {
$scope.serverComment = result;
});
};
};
});
In the above example, the new instance of the controller uses the current params of the router to load the necessary data.
This my javascript part i am not able to get any response from $http.get
can anyone suggest a solution
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:3000/load")
.success(function(response) {$scope.names = response;});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="data in names">
{{ data.name + ', ' + data.age }}
</li>
</ul>
</div>
From AngularJS documentation https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
No localhost:3000, just use '/load'.
No '.success', use '.then'
Try this
var Response = $http.get( $window.location.pathname + your url); //put your url here
Response.success( function ( data ) {
$scope.Names = data;
} );
Response.error( function ( data ) {
$scope.error = data;
} );
Your angular code has to change like #Dmitri Algazin has suggested. Check below code and the JS Fiddle
$http.get("http://localhost:3000/load")
.then(function(response) {$scope.names = response.data;});
JSfiddle
I am new to angular and I am trying to load a CSV list inside a factory and then convert it to json. I am using Papaparse (CSV to json library) inside the factory. When I console log the factory I get the array of objects which is exactly what I want but when I pass it inside my controller I get a single object which holds all the data.
This is my factory
(function() {
var app = angular.module('test');
app.factory('testFactory', ['$http', function($http) {
var url = 'my-list.csv';
var getContact = function() {
return $http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
return results.data;
}
});
});
};
return {
getContact: getContact
};
}]);
}());
And this is my controller
(function() {
var app = angular.module('test');
app.controller('testCtrl', ['$scope', 'testFactory', function($scope, testFactory) {
testFactory.getContact().then(function(data) {
$scope.contacts = data;
console.log(data);
});
}]);
}());
I want be able to do something like this inside my view
{{ contact.firstname }}
The issue is the order of resolution. Inspecting the console statements shows that you're assigning $scope.contacts to the resolution of the $http.get promise, and not the actual parsing.
Instead of returning the $http.get promise, return a deferred promise and resolve at the end of parsing:
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
Papa.parse(data, {
header: true,
complete: function(results) {
console.log(results.data);
parsePromise.resolve(results.data);
}
});
});
return parsePromise.promise;
See working demo here.
Update: As per the comments, you could use .then to chain promises instead of creating a new deferred. The plunkr has both, you can use the changelog to toggle methods.
i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});
I'd like to filter the JSON being displayed by the route param provided. I have a list page which displays all of the json data and a detail page which I would like to just display the json matching the id in the routeparam.
This is my service:
app.factory("HC", ["$resource", function($resource) {
return {
API: $resource('/api/hc')
}
}]);
This is my controller which is working for displaying all of the results. How could I filter these by the requestParams?
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', function ($scope, HC, $resource, $routeParams ) {
HC.API.query(function(results) {
$scope.services = results;
});
$scope.services = []
}]);
And here are my routes
.when('/services', {
templateUrl: 'templates/services.html',
controller: 'servicesController'
})
.when('/services/:serviceId', {
templateUrl: 'templates/servicedetail.html',
controller: 'servicesDetail'
})
Your json is not valid but in case it has format like that :
{ "_id" : "53bc36b8b7bbbf77208dec62", "name" : "this is from the client", "__v" : 0 }
you can use filterFilter service please see demo here http://jsbin.com/somob/1/edit?html,js,output
but the best option is send serviceId to server and get a single service from server instead array of services and filter them after
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', 'filterFilter',
function ($scope, HC, $resource, $routeParams, filterFilter) {
$scope.services = [];
HC.API.query(function (results) {
$scope.services = results;
});
$scope.serviceId = $routeParams.serviceId;
$scope.serviceById = filterFilter($scope.services, {
_id: $routeParams.serviceId
});
}]);
html:
<!--just for testing -->
<p>ServiceId : {{serviceId }}</p>
<pre>{{serviceById |json}}</pre>