The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});
Related
I basically need to call a server that's will return me a JSON structure before load the controller.
I was using many methods to archive that, but it's not working. It's don't show me any error and the page got blank. Any clue about what's going on ?
This is my controller..
angular
.module('app',[
'ngAnimate',
'ui.router',
'ui.bootstrap',
'ngCookies'
])
.run(function($rootScope) {
$rootScope.backendServer = "http://localhost:5000/";
})
.config(['$urlRouterProvider','$stateProvider', function($urlRouterProvider,$stateProvider) {
$stateProvider
.state('cms',{
url: '/my',
templateUrl: './app/templates/my.html',
controller : 'my',
resolve: {
dbState: function ($q) {
var defer = $q.defer();
Database.check().then(function (s) {
defer.resolve(s);
});
return defer.promise;
}
}
})
}])
.controller(function ($scope){
})
...and this is my service:
angular
.module('app')
.factory('Database',['$http', '$rootScope','$q', function($http, $rootScope, $q) {
return {
check: function () {
var call = $rootScope.backendServer + 'cms/database/check';
return $http.get(call);
}
}
}]);
don't create a defer object when you already returning a promise. so remove the defer and just return the factory function
also, inject the Database service to resolve
resolve: {
dbState: function(Database) {
return Database.check()
}
}
In the controller catch it like this
.controller("ctrl", function($scope, dbState) {
console.log(dbState.data)
})
Demo
I'm trying to get the data from a json file.
i have a file, factory1.js
myApp.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
and then i have another file, view1.js
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.get("data.json")
.then(function(response) {
$scope.myWelcome = response.data;
console.log($scope.myWelcome)
});
}]);
i have one folder with each of the json, factory and controller files in it.
when i run this the error it is returning says...
angular.js:13708 Error: [$injector:unpr] Unknown provider: mainInfoProvider <- mainInfo <- View1Ctrl
where am i going wrong?
Working fine. This solves your problem i hope so.
'use strict';
var app=angular.module('myApp.view1', ['ngRoute'])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
app.factory('mainInfo',
function($http) {
var obj={};
obj.method =function(){
return $http.get('tag.json')
}
return obj;
})
app.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.method().success(function(response) {
$scope.myWelcome = response;
});
}]);
var app=angular.module('myApp.view1', ['ngRoute']);
app.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
define one variable and assign your module to that variable and bind the variable to the factory.if you have module with name myApp inject that module in to myapp.view1 module
like
angular.module('myApp.view1', ['ngRoute','myApp'])
Register mainInfo inside Angular module, if it's a different module.
view1.js
angular.module('myApp.view1', ['ngRoute', 'myApp']);
You have not assigned your module to a variable.
var myApp = angular.module('myApp.view1', ['ngRoute']) ...
Then use myApp.factory
myApp.factory('mainInfo', [...
see this plunkr for quick understanding.
I am trying to use the code from here to show routes only when a promise is TRUE
I am following this for my directory structure
app
- Orders
-orders.html
-OrderController.js
-OrderService.js
Main-Config [app.js]
var myApp = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap','myApp.OrderController']);
myApp.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/orders', {
templateUrl: 'orders/orders.html',
controller: 'OrderController',
resolve:{
customerExpenses: function(OrderService){
return OrderService.getOrders($route.current.params.customerName);
}
}
})
})
OrderService.js
angular.module('myApp').factory('OrderService', ['$http', function($http) {
var sdo = {
getNames: function() {
var promise = $http({
method: 'GET',
url: ''
});
promise.success(function(data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}]);
I have tried the Accepted answer from here, and one of the suggestion from another SO article
angular.module('myApp')
.service('FooService', function(){
//...etc
})
.config(function(FooServiceProvider){
//...etc
});
As I have my service in a different file, I am trying to determine if I can use it in app.js file without using provider or is that the only way to use service in app.config?
UPDATE 1:
If i want to use the service in a controller
angular.module('myApp.OrderController',[]).controller('OrderController', function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
});
I get OrderService not available
Have tried this:
angular.module('myApp.OrderController',[]).controller('OrderController', ['$scope','OrderService',function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
}]);
followed example :
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
but can not use my service. my controller and service are in different files
I added this question here as I feel they are somewaht related.
You have not injected your service OrderService, change your code in very first line
var myApp = angular.module('myApp', ['ngRoute','ngAnimate', ....'OrderService'])
myApp.config(function($routeProvider, $locationProvider, OrderService){
....
})
Rest of the code looks good
I'm following a PluralSight tutorial on AngularJS fundamentals. Though I'm using a much different structure as I seem to have a much newer version of Angular Seed.
I'm trying to inject a service into controller using the same syntax structure as I have done before, which was working fine, but this one brings the following error:
Error: [$injector:unpr] Unknown provider: eventDataProvider <- eventData
viewEventDetails.js (Controller)
'use strict';
angular.module('myApp.viewEventDetails', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/viewEventDetails', {
templateUrl: 'viewEventDetails/viewEventDetails.html',
controller: 'viewEventDetailsCtrl'
});
}])
.controller('viewEventDetailsCtrl', ['$scope', 'eventData', function($scope, eventData) {
$scope.sortorder = '-upVoteCount';
$scope.event = eventData.getEvent(function (event) {
$scope.event = event;
});
$scope.upVoteSession = function (session) {
session.upVoteCount++;
};
$scope.downVoteSession = function (session) {
session.upVoteCount--;
};
}
]);
EventData.js (Service)
angular.module('myApp.services', [])
.factory('eventData', ['$http', '$log', function ($http, $log) {
return {
getEvent: function () {
$http({ method: 'get', url: '/data/event/1' })
.success(function (data, status, headers, config) {
$log.warn(data, status, headers(), config);
})
.error(function (data, status, headers, config) {
$log.warn(data, status, headers(), config);
});
}
}
}]
);
app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'ngSanitize',
'myApp.filters',
'myApp.services',
'myApp.viewNewEvent',
'myApp.viewEventDetails',
'myApp.viewEditProfile',
'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
you need to inject the myApp.services into your module that the controller is in, since the modules are different.
i.e.
angular.module('myApp.viewEventDetails', ['ngRoute', 'myApp.services'])
I am having a hard time to access a service inside a directive. I define my service via $http and $q, and inject it into my directive. But I can;t get the directive to access the service.
service.js
'use strict';
var app = angular.module('App.services', []);
app.factory('Classification', function($http,$q) {
return {
query: function getAll() {
var deferred = $q.defer();
$http.get('index.php/classifications').then(function(classi) {
deferred.resolve(classi.data);
}, function getWebsitesError(reason) {
deferred.reject(reason);
});
return deferred.promise;
}
};
});
app.js
'use strict';
/* App Module */
var app = angular.module('App', ['App.controllers', 'App.services', 'App.directives', 'ui']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'partials/welcome.html'}).
when('/websites/:websiteId', {templateUrl: 'partials/website/details.html', controller: 'WebsiteDetailsCtrl'}).
otherwise({redirectTo: '/'});
}]);
and my directive.js :
'use strict';
var app = angular.module('App.directives', ['App.services']);
app.directive("regionselect",['Classification', '$compile', function($compile, Classification){
Classification.query();<-- Throw an exception : has no method query()
return{
restrict : "E",
templateUrl : "/js/directives/locationSelect3.html",
transclude: true,
compile: function (tElement, tAttr, transclude){
var loaded = false;
}
};
}]);
Any idea what I am doing wrong?
Could it be the ordering?
app.directive("regionselect",['Classification', '$compile', function($compile, Classification){
You declare
['Classification', '$compile',
but the the function says
function($compile, Classification){
Which is backwards.