Angular js / angular ui router 0.2.15
I am trying to pass complex js array into the controller using $state.go
Following is my code can you help. looks like following code throwing error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.28/$injector/unpr?p0=servicesProvider%20%3C-%20services
.js file
var services = {complex type};
$state.go("linearOfferProcess", {'services': services});
in my route.js
state('linearOfferProcess', {
url: '/linearOfferProcessor',
templateUrl: '/partials/linear_process.html',
controller: 'linearProcessController',
services:
function($stateParams) {
return $stateParams.services;
}
}
controller
angular.module('app').controller('linearOfferProcessController',function($scope) {
$scope.services = services;
});
Unfortunately I don't know any possible of accomplishing this, but you could try doing it using a Factory. I made a small mockup for you, in the container I'm storing the services and creating a unique ID for every complex object. So you can retrieve it whenever you want.
angular.module('app').factory('ServicesContainer', function() {
var counter = 1;
return {
container: {},
add: function(services) {
container[counter] = services;
return counter;
}
};
});
angular.module('app').controller('SomeController', function(ServicesContainer, $state) {
var id = ServicesContainer.add({ complex object });
$state.go('services', {
id: id
});
});
angular.module('app').config(function($stateProvider) {
$stateProvider.state('services', {
url: '/{id}',
onEnter: function(ServicesContainer, $stateParams, $log) {
$log.info('Services', ServicesContainer[$stateParams.id]);
}
});
});
Related
(My plunkr code resides at http://plnkr.co/edit/6KU3GblQtMdRAx3v3USV?p=preview)
I'm trying to create a Search bar (in navigation) which should ultimately hit the backend REST API. The input search button when clicked on input 'alpha' would trigger a route to products/search/0?searchtext=alpha
Clicking on the button triggers a route change, which should do resolve as follows:
.when("/products/search/:page", {
templateUrl: "products.html",
controller: "ProductsSearchController",
resolve: {
// Define all the dependencies here
ProdSearchServ : "ProdSearchService",
// Now define the resolve function
resultData : function(ProdSearchServ) {
return ProdSearchServ.searchProducts();
}
}
})
However, I'm getting the following error
angular.js:9784 Error: [$injector:unpr] Unknown provider: ProdSearchServProvider <- ProdSearchServ
I believe I'm doing most of the things as per conventions, may be I'm missing something here?
I'm copying script.js code below (also in plnkr link above). It has all the route configuration and the controllers defined.
(function(){
// jargoViewer Create a new Angular Module
// This would go into the html tag for index.html
var app = angular.module("jargoViewer", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "NavController"
})
.when("/products/search/:page", {
templateUrl: "products.html",
controller: "ProductsSearchController",
resolve: {
// Define all the dependencies here
ProdSearchServ : "ProdSearchService",
// Now define the resolve function
resultData : function(ProdSearchServ) {
return ProdSearchServ.searchProducts();
}
}
})
.otherwise({redirectTo:"/main"});
});
}());
// Nav Controller
(function() {
var app = angular.module("jargoViewer");
var NavController = function($scope, $location) {
// Function to invoke the Prod search based on input
$scope.search = function() {
console.log("searchText : " + $scope.searchtext);
$location.path("products/search/0").search({searchtext: $scope.searchtext});
};
};
app.controller("NavController", NavController);
}());
// Define the Prod Search Service here
(function() {
// Get reference to the app
var app = angular.module("jargoViewer");
// Create the factory
app.factory('ProdSearchService', function($routeParams, $http, $q) {
var searchProducts = function() {
pageNum = 0;
searchParam = '';
if (('page' in $routeParams) && (typeof $routeParams.page === 'number')) {
pageNum = $routeParams.page;
}
// Check if the router Param contains the field searchtext, if so, check if its a string
if (('searchtext' in $routeParams) && (typeof $routeParams.searchtext === 'string')) {
searchParam = $scope.routeParam.searchtext;
}
// Now make the http API hit to fetch the products
var request = $http({
method: "get",
url: "http://abcd.com/products/search/" + pageNum,
params: {
search: searchParam
},
});
return(request.then(handleSuccess, handleError));
};
function handleError(response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (
! angular.isObject(response.data) ||
! response.data.message
) {
return($q.reject( "An unknown error occurred."));
}
// Otherwise, use expected error message.
return($q.reject(response.data.message));
}
// I transform the successful response, unwrapping the application data
// from the API response payload.
function handleSuccess(response) {
if(response.data.error == true) {
return($q.reject(response.data.message));
}
return(response.data.data);
}
return {
searchProducts : searchProducts
};
});
}());
// Define the Products Search Controller below
(function() {
var app = angular.module("jargoViewer");
//var ProductController = function($scope) {
var ProductsSearchController = function($scope, $routeParams, ProdSearchService) {
// Nothing to do really here
};
app.controller("ProductsSearchController", ProductsSearchController);
}());
This caused by your bizarre naming conventions. Sometimes ProdSearchServ and sometimes ProdSearchService.
If you just pick one and use it consistantly then you won't run into these types of errors.
Fixed Plunker
In particular you create the service with the name ProdSearchService and then attempt to use it with a different name:
app.factory('ProdSearchService',
//vs
resultData : function(ProdSearchServ) {
I imagine you we under the impression that this code would fix it for you. However, this only applies to dependencies passed into the controller, not functions in general. For services which already exist, you do not need to define them specially like this; instead simply use the correct name in the controller.
// Define all the dependencies here
ProdSearchServ : "ProdSearchService",
I think you don't need to define the dependency when you say
// Define all the dependencies here
ProdSearchServ : "ProdSearchService",
Just do this:
.when("/products/search/:page", {
templateUrl: "products.html",
controller: "ProductsSearchController",
resolve: {
resultData : function(ProdSearchService) { //as you defined it before
return ProdSearchService.searchProducts();
}
}
})
There is a similar question here
I am getting more familiar with ui-router and using .then as opposed to .success. However, I am having some difficulty passing in a service to resolve. Currently, resolve is blocking access to the controller. My goal is to get individual information from each user when they are selected.
I referenced the resolve through the ui-router wiki https://github.com/angular-ui/ui-router/wiki#resolve . Translations 2 seems to resemble how I am using my service
(function() {
'use strict';
angular
.module('app.orders')
.config(config);
function config($stateProvider) {
$stateProvider
.state('orders',{
url:'/customers:customerId',
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
customerFactory: 'customerFactory',
customerId: function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}
}
})
};
})();
I am referencing the service call in customerId of resolve This is what I am passing to the ordersController.
Here is my service that is getting my customers.
(function() {
angular
.module('app.services',[])
.factory('customersFactory', customersFactory);
function customersFactory($http, $log, $q) {
return {
getCustomers: getCustomers
};
function getCustomers(){
var defer = $q.defer();
return $http.get('./Services/customers.json',{catch: true})
.then(getCustomerListComplete)
.catch(getCustomerListFailed);
function getCustomerListComplete(response) {
console.log('response.data',response.data);
// defer.resolve(response.data);
return response.data;
}
function getCustomerListFailed(error) {
console.log('error', error);
}
}
}
}());
Here is my controller. It is pretty small for right now. I am hoping to access it first. I do have customerId injected into it however.
(function() {
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
function OrdersController($stateParams, customerId) {
console.log(customerId);
var vm = this;
vm.title = "Customer Orders";
vm.customer = null;
}
}());
******* Update *****
I found reviewed some code from when I was using ng-Route.
In this I used $route the same way that I am hoping to use $stateParams.
resolve: {
cityDetails:['cacFindCountry','$route', function(cacFindCountry,$route){
var countryCode = $route.current.params.countryCode;
console.log('cityDetails',cacFindCountry(countryCode))
return cacFindCountry(countryCode);
}],
countryNeighbors : ['cacFindNeighbors','$route', function(cacFindNeighbors,$route) {
var countryCode = $route.current.params.countryCode;
// pushes country code into neighbors
return cacFindNeighbors(countryCode);
}],
countryDetails : ['cacCountries', '$route', function(cacCountries, $route) {
var countryCode = $route.current.params.countryCode;
console.log(countryCode);
console.log(cacCountries(countryCode));
// need to get specific country info
// return cacCountries(countryCode);
return countryCode;
}]
}
I'm following the official examples to fetch the user before the angular controller is fired but the controller is never fired when using this method. If I remove the resolve: state_resolver line the controller fires which means my resolver has something wrong. Any ideas what am I doing wrong here?
.config(function($stateProvider) {
var state_resolver;
state_resolver = {
"current_user": [
"simpleLogin", function(simpleLogin) {
return simpleLogin.$getCurrentUser();
}
]
};
return $stateProvider.state("dash", {
url: "/dash",
templateUrl: "templates/dash.html",
controller: "DashCtrl",
resolve: state_resolver
});
});
If the following example using $timeout works, then you probably have an issue with your simpleLogin service which does not respond.
.config(function($stateProvider) {
var state_resolver;
state_resolver = {
"current_user": function($timeout) {
return $timeout(function () {console.log('OK');}, 5000);
}
};
I'm new to AngularJS and just building an app to learn it. My app calls a REST API and right now I have the hostname hard coded in the app. I want to make this in app setting (and maybe later have somewhere to configure it). I thought I'd start with a constant. Should it go in my app.js like this? If so, I'm not sure of the syntax for adding it to the .config settings with $routeProvider there too
(function () {
// Define module and add dependencies inside []
var app = angular.module("haClient", ["ngRoute"]);
app.constant('hostname', 'http://192.192.192.192:8176');
app.config(function ($routeProvider) {
$routeProvider
// Register routes
// Main route
.when("/main", {
templateUrl: "main.html",
controller: "MainController"//,
//activeTab: 'home'
})
// Device List
.when("/devices", {
templateUrl: "devicelist.html",
controller: "DeviceListController"
})
// Device details (param is device name)
.when("/device/:devicename", {
templateUrl: "device.html",
controller: "DeviceController"
})
// Invalid URL's get sent back to main route
.otherwise({ redirectTo: "/main" });
}); // End App Config
}());
This is the module that needs to use it (called from controllers):
(function () {
var deviceCtrl = function ($http) {
var getDevices = function () {
return $http.get("http://192.192.192.192:8176/devices.json/")
.then(function (response) {
return response.data;
});
};
// get details and return a promise
var getDeviceDetails = function (deviceName) {
return $http.get("http://192.192.192.192:8176/devices/" + deviceName + ".json/")
.then(function (response) {
return response.data;
});
};
// Public API
return {
getDeviceDetails: getDeviceDetails,
getDevices: getDevices
};
};
var module = angular.module("haClient");
}());
Can someone enlighten em on the best way to set it and get it?
Thanks
I currently do this by using templates to build the root .html file in the backend. Eg, using doT templates in node.js, I put this below my other js includes:
<!-- load any templated constants -->
<script>
angular.module('mymod').constant('globals', {
api: '{{=it.api}}'
});
</script>
This way my backend can work out the logic of where the client needs to point to. In order to use the value in another service or controller, you simply inject the constant by name:
angular.module('somemod', []).factory('myservice', ['globals', function(globals){
// use globals.api or what ever you set here for example
}]);
The best place to do configuration is in a Provider and inside your config block.
Providers expose an API that allows you to configure your service before it's injected into your controllers and directives.
Suppose you have a service called myService that you want injected into your controller function like this:
app.controller('ctrl', function($scope, myService) { ...});
And myService is responsible for retrieving data through web API calls. Let's further assume that you would like to configure your service with the root URL htt://servername/, since all calls will share the same host name.
You can define your myServiceProvider like this:
app.provider('myService', function(){
var webapiurl;
this.setWebServiceUrl = function (url) {
webapiurl = url;
}
// the injector will call the $get function to create the singleton service that will be injected
this.$get = function( /*injectables*/) {
return {
getData: function() {... Use webapiurl ...}
}
}
});
Then in your config function, configure your provider:
app.config(function(myServiceProvider){
myServiceProvider.setWebServiceUrl('htt://servername');
});
Finally you can inject the service anywhere it can be injected:
app.controller('ctrl', function($scope, myService) {
$scope.data = myService.getData();
});
I couldn't get the supplied answers to work (no reason to think they wouldn't). here's what I did.
My main app.js (constants section)
(function () {
// Define module and add dependencies inside []
var app = angular.module("haClient", ["ngRoute"]);
//constants
app.constant('mySettings', {
baseURL: 'http://192.192.192.192:8176',
otherSetting: 'XYZ'
});
app.config(function ($routeProvider) {
$routeProvider
// Register routes
// Main route
.when("/main", {
templateUrl: "main.html",
controller: "MainController"//,
//activeTab: 'home'
})
// Device List
.when("/devices", {
templateUrl: "devicelist.html",
controller: "DeviceListController"
})
// Device details (param is device name)
.when("/device/:devicename", {
templateUrl: "device.html",
controller: "DeviceController"
})
// Invalid URL's get sent back to main route
.otherwise({ redirectTo: "/main" });
}); // End App Config
}());
In my service (added mySettings as a dependency and then just used mySettings.baseURL):
(function () {
var deviceCtrl = function ($http, $log, mySettings) {
$log.info("DeviceCtrl - baseURL: " + mySettings.baseURL);
// get device list and return a promise
var getDevices = function () {
return $http.get(mySettings.baseURL + "/devices.json")
.then(function (response) {
return response.data;
});
};
// get details and return a promise
var getDeviceDetails = function (deviceName) {
$log.info("DeviceCtrl - Getting device info for " + deviceName);
return $http.get(mySettings.baseURL + "/devices/" + deviceName + ".json")
.then(function (response) {
return response.data;
});
};
// Public API
return {
getDeviceDetails: getDeviceDetails,
getDevices: getDevices
};
};
var module = angular.module("haClient");
module.factory("deviceCtrl", deviceCtrl);
}());
I'm certainly no expert (as is clear from not being able to get supplied answers working), and I'm not sure (yet) if there are any drawbacks to this method. It allowed me to get on with my project and learn more of Angular, so I went with it.
Regards
Mark
I have used another module and injected it into app module like this
Create constant.js and include that in your index.html & add following code inside that
angular.module('constantsModule', []).constant('BASEURL', 'http://google.com');
Inside app.js, inject 'constantsModule' so that all constants inside it will be available for 'haClient'
angular.module('haClient', [
'constantsModule'
])
.config(function ($routeProvider) {
.when('/', {
templateUrl: 'views/landing.html',
controller: 'landingCtrl'
})
});
Inside landingCtrl, since its in scope of 'haClient', we can inject BASEURL constant from 'constantsModule'
angular.module('haClient').controller('landingCtrl', function ($scope, BASEURL) {
// just to show, how to access it inside controller
$scope.baseurl = BASEURL;
});
I want to pre-load data in my controller. I am doing this using resolve in the routeprovider:
.when('/customers', {
controller: 'CustomerController', templateUrl: '/Customer/Index', resolve: {
countries: CustomerController.loadCountries,
genders: CustomerController.loadGenders,
}
})
As you can see I have two objects which will be injected into my controller, countries and gender. All this works fine.
What I want to do is, I want those objects to be part of one object: listData. I've tried:
.when('/customers', {
controller: 'CustomerController', templateUrl: '/Customer/Index', resolve: {
listData: {
countries: CustomerController.loadCountries,
genders: CustomerController.loadGenders
}
}
})
but this doesn't work: Argument 'fn' is not a function, got Object.
What is the right syntax / approach to accomplish this?
If you pass an object to a key, you must have a function as the value :
listData: function () {
// you need to inject
var deferred = $q.defer();
var listData = {};
// these should be services, btw !
CustomerController.loadCountries.then(function (countries) {
listData.countries = countries;
// resolve when you have both
if (listData.genders) deferred.resolve(listData);
});
CustomerController.loadGenders.then(function (genders) {
listData.genders = genders;
if (listData.countries) deferred.resolve(listData);
});
return deferred.promise;
}