I am building a small mobile app blog with ionic and angular but when i try to make a resource query with manually injected params i have a bad url string. meaning angular is not passing my syntax correctly or i am making a bad mistake.
Here is my code
angular.module('starter.posts', ['ionic','ngResource'])
.factory('Post', function ($resource) {
return $resource('http://example.org/wp-json/:params');
});
app.controller('HomeCtrl', function ($scope, $state, $ionicSideMenuDelegate, Post) {
"use strict";
/* Items for left side menu. */
$scope.posts = Post.query({params: "posts?filter[posts_per_page]=3"})
})
and the error log show the bellow error
http://example.org/wp-json/posts%3Ffilter%5Bposts_per_page%5D=3 Failed to load resource: the server responded with a status of 404 (Not Found)
which simply means that it did not translate the url correctly. How can i fix this so the url can be in the bellow format
http://example.org/wp-json/posts?filter[posts_per_page]=3
I am new to angular trying to simulate an entire wordpress blog with angular.
I usually do something like this, passing a js object in:
usersFactory.get = function (request) {
var operation= $http({url: urlBase, method:'get', params:request });
perhaps you should add posts to your resource url
$resource('http://example.org/wp-json/posts:params');
and pass an object like this
var filter={};
filer.posts_per_page=3
in as your params
I was able to figure the right syntax by using the code below,
Post.query({'filter[posts_per_page]': 20, 'page' : $scope.pageNum}, function (data, responseHeaders)
Related
I'm totally new to the Restangular and trying to learn it by implementing a simple application by calling a webapi. I'm able to call this service with simple $http service and getting the correct response.
The code I have written is as below.
I have googled the issue to find the solution but no like.
var myApp = angular.module('myApp', ['restangular']);
myApp.config(function (RestangularProvider) {
var newBaseUrl = "";
newBaseUrl = 'http://localhost:37103/api/'
RestangularProvider.setBaseUrl(newBaseUrl);
})
myApp.controller("myCtrl", function ($scope, Restangular) {
$scope.data = "Default Value"
$scope.data = Restangular.one("employee").get();
})
The error which I'm getting on chromes console is as below
angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=myApp&p1=Error%3A%2…0Bc%20(http%3A%2F%2Flocalhost%3A37103%2FSource%2Fangular.min.js%3A21%3A179)
The above error is clickable and it says may be the file is mot included. But I have included the restangular.js file and I could see it getting loaded in the network tab.
Thanks!
For this issue I found something was wrong in the restangular.js file which I downloaded. I replaced it with the cdn tag cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.js and it worked. Its very strange.
I'm building a rest api with fosrestbundle and I manage the frontend with angular and Twig template. One on my url address looks like this :
http://mywebsite/myroute/idContain
When I load the url in my browser, in a twig template (kind of html), I retrieve the parameter "idContain" (comming from a fosrestbundle controller) with ng-init of angularjs like this :
<div class="container-fluid" ng-init="getContainByID({{ idContain }})">
//...lot html div with angularjs directives
</div>
And immediately, ng-init will go to my angularJS app finds getContainByID(idContain) to run it.
This one looks like this :
angular.module("myApp", ["ngSanitize", 'angular.filter', 'ui.tinymce', ...])
.config(function($interpolateProvider, ...) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
})
.controller("myCtrl",function ($filter,..., myService)
{
// lot of code...
$scope.getContainByID = function(idContain)
{
$scope.currentContain = myService.getContains(idContain);
$scope.containRoot = $scope.currentContain.contain.containRoot;
...
}
// lot of code...
}
The fact is that, myService.getContains(idContain) come from my rest service looking like this :
angular.module("MyServiceRest", ['ngResource'])
.factory("myService", function ($rootScope, $resource) {
var apiData = $resource(
"/api", {},
{
...
"getContains": {method: 'GET', isArray: false, url: "mywebsite/api/myroute/:containid"}
...
});
return {
getContains: function (idContain) {
return apiData.getContains({containid: idContain});
}
}
});
Now the problem is, when I run my angularjs App, $scope.containRoot doesn't wait until myService.getContains(idContain) (coming from my asynchroeous $resource service) finished to load, and caused errors making my webapp crash.
How can I do, to force $scope.containRoot and the rest of my angular code to waiting until myService.getContains(idContain) (connected to the api resource) completly finished to load before continuing ?
$resource makes an asynchronous request but immediately reurns an empty object or array.
There are numerous ways you could handle your issue.
One would be not to worry about declaring $scope.containRoot and just using currentContain.contain.containRoot in the view. This property will get rendered after the request is received
Another is to use the $promise that is also returned by $resource and assign the scope property in promise callback
$scope.currentContain = myService.getContains(idContain);
$scope.currentContain.$promise.then(function(){
$scope.containRoot = $scope.currentContain.contain.containRoot;
});
Another is to use a routing resolve based on the same promise so the route( or state depending on router) is noot entered until the request is complete
I'm new on AngularJS. I would like to know what is the best way to use pure AngularJS to initiate a controller that uses a service that makes an HTTP request to an external source and as a response receives a JSON object.
The controller is being used to fetch information that will be shown as part of the landing page (welcome information).
I have tried:
In the HTML invoke the function with the ng-init, with alias for the controller and without alias.
In the controller make the explicit call to the service, and in the configuration of routes, resolve primitive to call the Service and save it a a variable at the configuration file.
In the controller receive as a parameter the response of the service and in the configuration of routes, use the resolve primitive to call the Service and save it as a variable with the name of the parameter that the controller receives.
In the controller save the response as a $scope variable, but it is always undefined an nothing is bound to the HTML. Is it necessary to create a value or a directive or something for saving an object in the scope? Also tried doing it at the service with $scope as parameter with the same results (undefined $scope variable).
These options effectively trigger the HTTP request and pass through the lines of the controller function. The problem is that the response is not available for the controller. Under debug mode I can only see that is an object but it doesn't behaves as a JSON object so can't access to none of the properties.
I used the .then at the controller, but although now the data is saved in the $scope, it shows [OBJECT OBJECT] and I can't access to the properties of the JSON object that is saved as the response of the http request. Any ideas?
The function of the service that makes the request like the following:
myAppModule.factory('ClimateService', function ($http) {
return {
getLocation: function () {
return $http.get("some_url/json")
then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
//
});
}
}
});
Under debug I can see the 200 response and the JSON of it. Content-Type:application/json; charset=utf-8
After several changes, none of them are triggering and I am getting an injection error. I have included the local angular-routes in the HTML header, fetched with bower.jason to the project at NetBeans. And included as the first dependency or parameter to the ngRoute
angular.module('app',['ngRoute', ...
angular.module('app.routes', ['ngRoute', 'app.core'])
.config(config);
angular.module('app.core', []);
By the way, the Angello project at GitHub injects neither services nor much parameters and the book doesn't cover this topic in depth.
Is it the version of AngularJS?
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=app&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.4.8%2F%24injector%2Fmodulerr%3Fp0%3Dapp.config%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.4.8%252F%2524injector%252Fnomod%253Fp0%253Dapp.config%250A%2520%2520%2520%2520at%2520Error%2520(native)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A6%253A416%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A24%253A186%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A23%253A251)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A23%253A494%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A38%253A117%250A%2520%2520%2520%2520at%2520n%2520(http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A7%253A333)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A37%253A488)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A38%253A134%250A%2520%2520%2520%2520at%2520n%2520(http%253A%252F%252Flocalhost%253A8383%252Fapp_demo_app%252Fbower_components%252Fangular%252Fangular.min.js%253A7%253A333)%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A6%3A416%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A38%3A391%0A%20%20%20%20at%20n%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A7%3A333)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A37%3A488)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A38%3A134%0A%20%20%20%20at%20n%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A7%3A333)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A37%3A488)%0A%20%20%20%20at%20eb%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A41%3A249)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A8383%2Fapp_demo_app%2Fbower_components%2Fangular%2Fangular.min.js%3A19%3A463) (23:05:42:235 | error, javascrip
It's a bit tricky because you have to use promises (.then), but here's a super simple 'get' example.
On the Service:
function mainService($http) {
this.getData = function () {
return $http.get('/api/yourUrl') //a basic 'get' api call
.then(function (response) { //it takes time, so include a promise
return response.data;
});
};
}
And the Controller:
function homeController($scope, friendService) {
$scope.getData = function () {
mainService.getData()
.then(function (data) { //you also need a promise on controller
$scope.ourData = data; //finally put what you get on your scope
});
};
}
Note these examples don't show the defining of the controller and the service - let me know if you're confused.
let's suppose you'll use $http service to request data.
angular.module('app.core', [])
.controller('CoreController', CoreController);
CoreController.$inject = ['$scope', '$http'];
function CoreController($scope, $http) {
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
alert('something odd happens.');
});
};
in your html
<div ng-bind-html="data">
</div>
or if you want to fill a form input:
<input type="text" ng-model="data" />
From what I understood, I am suggesting few things to keep in mind . May be its not what you are looking for but it might help.
ng-init is called as the very first thing inside a controller. You can use promise in case you have to keep things in sync.
If you dont want to get into promise, simply do $http call from controller as it by default handles promise using .success & .error function.
You can't expect some $scope variable to be valid under html if it is inside service. Refer docs.
var mainApp = angular.module("mainApp",[]);
mainApp.controller("serviceController",function($scope,$http){
$http.get("/fetchData_url/").success(function(response){
$scope.data = response;
});
});
I am working on a sample application using angular js. I am a newbie , so please bear with me
I have the following code in my controllers.js :
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', '$http', function ($scope, $http) {
$http.get('js/data.json').success(function (data) {
$scope.artists = data;
$scope.artistOrder = 'name';
});
}]);
Here , i am using http.get to load json data into application from a text file as shown above.
I am using IE 9 and was allowed to use only that , not any browser.
When i execute the above code, i am encountering an error as stated below :
CSS3117: #font-face failed cross-origin request. Resource access is restricted
I am not sure what is a cross-origin request . I am wondering why a simple http get requested is getting failed.
Here are my queries :
What is a cross origin request? An example would be great
How this holds w.r.t my example above ?
What is the remedy/solution/alternative for this ?
Try defining a var outside the controller:
this.artists = {};
And then, inside the controller:
this.artists = data;
So the page can access that var. Otherside you can only access it inside the controller.
I am developing an application. In that i am retrieving the json data from an
external file using $http.get() method it worked fine. Now i am trying to use angular
restful services. it is working fine in filters, but when i use it in controller it is
displaying undefined.
//Service.js File
angular.module('calenderServices', ['ngResource']).
factory('Events', function($resource){
return $resource('/EventCalender/:File.json', {}, {
query: {method:'GET', params:{File:'events'}, isArray:true}
});
});
//This is my app Module
angular.module('calender', ['eventFilters','highlight','event','calenderServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('', {templateUrl: 'template.html', controller: MonthCtrl}).
otherwise({redirectTo: '/invalid'});
}]);
//This is my filter.js
angular.module('eventFilters', ['calenderServices']).filter('compare', function(Events) {
var events=Events.query();
alert(events[0].name); //it is displaying the name "Milestone1" });
//This is my controller.
function MonthCtrl($scope, Events){
var events=Events.query();
alert(events[0].name); //it is displaying undefined
}
//whenever i try to use the variable 'events' in controller, it is displaying undefined or null. But in filter it is working fine.
The following wont work because ngResource makes an asynchronous http request.
var events=Events.query();
alert(events[0].name); // <--- here events is an empty array
Usually all you need to do is the following and your data will be available to render in your view
$scope.events = Events.query()
It looks like a synchronous operation, but it isn't. This is angular's zen at work. You can learn the details from the docs.
To further process the data, you could also pass pass a success callback to the get method
Events.query(function(events){
// here you have access to the first event's name
console.log(events[0].name);
});
here's a working example: http://plnkr.co/edit/NDZ2JWjMUoUvtzEuRUho?p=preview