Creating a custom provider angularjs - javascript

I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');
mainApp.provider('choiceService', ['$http', function($http) {
return {
$get: function() {
return {
get: function(url) {
return $http.get(url);
}
};
}
};
}]);
config.js
var mainApp = angular.module('mainApp', [
'ui.router'
]);
mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
function($stateProvider, $urlRouterProvider, choiceServiceProvider) {
$stateProvider
.state('mainFlow', {
abstract: true,
url: '/base',
template: '<ui-view/>'
})
.state('mainFlow.choose-main', {
url: '',
templateUrl: '/choose_main.html',
})
.state('mainFlow.contact', {
controller: 'ContactFormController',
url: '/contact-details',
templateUrl: '/panel_contact_info.html',
})
.state('mainFlow.api', {
url: '/about-your-api',
controller: 'ApiFormController',
templateUrl: '/panel_about_your_api.html',
resolve: {
choice: function(choiceServiceProvider) {
return choiceServiceProvider.get('/api/yes-no-choice/');
},
other_choice: function(choiceServiceProvider){
return choiceServiceProvider.get('/api/my-other-choice/')
}
}
})
Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
'$scope',
'$state',
'choiceService',
function($scope, $state, choiceService) {
$scope.choices = choiceService;
}
]);

I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'

Related

AngularJS - How do I get the state name inside of state resolve function to load controller files?

I am making head ways into diving into my first complete AngularJS app using PHP and tailored toward an api-centric approach.
I have reached this point:
I want to be able to capture the state name inside $stateProvider below for purpose of passing to load function. However I am unable to get $rootScope.statename to be anything but undefined. I have removed this from my solution because I could not get it to help remove undefined from the load function alert statement.
How do I capture (risk or actionitem) as the desired state name to be able to pass to the load function?
app.js -Removed code snippet
app.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.statename = $state.current;
}]);
app.js
angular.module('Action', ['datatables', 'datatables.scroller', 'ngResource']);
angular.module('Risk', ['datatables', 'datatables.scroller', 'ngResource']);
var app = angular.module('Main', ['ui.router', 'oc.lazyLoad', 'datatables', 'ngResource', 'Action', 'Risk']);
app.config(['$ocLazyLoadProvider', '$stateProvider', '$urlRouterProvider', function($ocLazyLoadProvider, $stateProvider, $urlRouterProvider){
configRoutes($stateProvider, $urlRouterProvider, $ocLazyLoadProvider);
}]);
route-config.js
function load ($ocLazyLoad, $q, $rootScope){
var deferred = $q.defer();
try{
$ocLazyLoad.load($rootScope.statename).then(function(){
deferred.resolve();
});
}
catch (ex){
deferred.reject(ex);
}
return deferred.promise;
}
function configRoutes($stateProvider, $urlRouterProvider, $ocLazyLoadProvider)
{
$urlRouterProvider
.when('action', 'action')
.when('issue', 'issue')
.when('lesson', 'lesson')
.when('opportunity', 'opporutnity')
.when('risk', 'risk')
.otherwise('main');
$ocLazyLoadProvider.config({
modules:
[{
name: 'action',
files: ['app/tool/action/ActionController.js']
},
{
name: 'risk',
files: ['app/tool/risk/RiskController.js']
}]
});
$stateProvider
.state('main', {
url: "/main",
//templateUrl: '/app/tool/home/home.html',
});
$stateProvider
.state('action', {
name: 'action', <----------------------state name I want to capture for this url
url: "/actionitems",
resolve: {
loadDependencies: ['$ocLazyLoad', '$q', '$rootScope', load]
},
templateUrl: '/app/tool/action/ActionItems.html'
});
$stateProvider
.state('risk', {
name: 'risk', <----------------------state name I want to capture for this url
url: "/risks",
resolve: {
loadDependencies: ['$ocLazyLoad', '$q', '$rootScope', load]
},
templateUrl: '/app/tool/risk/Risks.html'
});
}
$state.current has all the information about the current state, including the name. So $state.current.name will get you the information you need.
Just keep the code simple:
$stateProvider
.state('action', {
name: 'action', //<--state name I want to capture for this url
url: "/actionitems",
resolve: {
loadDependencies: function($ocLazyLoad) {
return $ocLazyLoad.load("action");
}
},
templateUrl: '/app/tool/action/ActionItems.html'
});
I added the allowed method to the resolve section and cleaned up the code to get the desired outcome. I declared a global state to capture the value in $state$.name
var state = '';
//route-config.js
function load($ocLazyLoad, $q)
{
var deferred = $q.defer();
try
{
$ocLazyLoad.load(state).then(function ()
{
deferred.resolve();
});
}
catch (ex)
{
deferred.reject(ex);
}
return deferred.promise;
}
function configRoutes($stateProvider, $urlRouterProvider, $ocLazyLoadProvider)
{
var res =
{
loadDependencies: ['$ocLazyLoad', '$q', load],
allowed: function ($state$)
{
state = $state$.name;
}
};
$urlRouterProvider
.when('action', 'action')
.when('issue', 'issue')
.when('lesson', 'lesson')
.when('opportunity', 'opporutnity')
.when('risk', 'risk')
.otherwise('main');
$ocLazyLoadProvider.config(
{
modules: [
{
name: 'action',
files: ['app/tool/action/ActionController.js']
},
{
name: 'risk',
files: ['app/tool/risk/RiskController.js']
}]
});
$stateProvider
.state('action',
{
url: "/actionitems",
resolve: res,
templateUrl: '/app/tool/action/ActionItems.html'
});
$stateProvider
.state('risk',
{
url: "/risks",
resolve: res,
templateUrl: '/app/tool/risk/Risks.html'
});
}

Ionic template does not work on mobile

I have been making an app in AngularJS with Angular-ui-router based on Ionic Framework. It works perfect on the desktop in every web browser, but it does not show anything on my mobile (after build I run it on 2 devices). The problem is that it doesn't load template inside ui-view.
I have got an index.html file, the body section is below (in head section there is everything included):
<body ng-app="starter">
<div ui-view=""></div>
</body>
And the part of app.js - run and config.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
.run(function($ionicPlatform, $rootScope, $location) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.back = function () {
history.back();
};
})
.config(function($stateProvider, $urlRouterProvider) {
"use strict";
$stateProvider
.state('connectionCheck', {
url: '/',
controller: ['$scope', '$location', '$http',
function($scope, $location, $http) {
$http.get('http://pingurl.com')
.success(function(data) {
jdata = data;
if (data.status === "success") {
$location.path('/login');
}else{
$location.path('/error');
}
})
.error(function() {
$location.path('/error');
});
$scope.retry = function() {
$location.path('/');
};
}
]
})
.state('login', {
url: '/login',
templateUrl: 'login.html'
})
.state('main', {
url: '/main',
templateUrl: 'main.html',
controller: ['$scope', '$location', '$localStorage',
function($scope, $location, $localStorage) {
$scope.username = $localStorage.username;
$scope.token = $localStorage.token;
$scope.email = $localStorage.email;
$scope.goToAlerts = function() {
$location.path('/alerts');
};
$scope.goToSettings = function() {
$location.path('/settings');
};
$scope.goToLocation = function() {
$location.path('/location');
};
$scope.goToSymptoms = function() {
$location.path('/symptoms');
};
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return "active"
} else {
return ""
}
};
}
]
})
.state('error', {
url: '/error',
templateUrl: 'error.html'
})
.state('register', {
url: '/register',
templateUrl: 'register.html',
})
.state('push', {
url: '/push',
templateUrl: 'push.html',
})
.state('alerts', {
url: '/alerts',
templateUrl: 'alerts.html'
})
.state('newSymptom', {
url: '/newSymptom',
templateUrl: 'newsymptom.html'
})
.state('symptoms', {
url: '/symptoms',
templateUrl: 'symptoms.html'
})
.state('newAlert', {
url: '/newalert',
templateUrl: 'newalert.html'
})
.state('settings', {
url: '/settings',
templateUrl: 'settings.html'
})
.state('location', {
url: '/location',
templateUrl: 'location.html'
});
$urlRouterProvider.otherwise('/');
}).
//some controllers goes here
What I have already checked/tried to do?
I put example content to index.html - it worked.
I tried chanage the name of ui-view and add them in templateURL values of each state.
I changed the .html files to exlude error in them, but it did not helped.
Can anyone more experienced with Ionic/Angular give me a hint what is wrong here?
I seem to notice that it's often due to the modules you're loading in. So It's likely in this line.
angular.module('starter', ['ionic', 'ngStorage', 'ngAnimate', 'naif.base64', 'ui.router'])
Try checking each module by making sure:
You added it to your index.html
it's being called correctly
it's up to date
You can figure out by removing each, one at a time and then seeing if it works on the device.
Also know that AngularJS out of the box uses AngularUI Router and this uses a thing called routing for views. The UI-Router uses a thing called states that is the most used but the unofficial way for AngularJS and Ionic uses their own view state system that is basically the same thing as the UI-Router just with the Ionic namespace. So that is something you need to look up or you may find yourself running into a lot of walls during you builds because you are calling ui.router and I bet it's what's confusing your app, so remove it.

Error: [$injector:unpr] Unknown provider in jasmine test when routeprovider service is injected in a controller

I have created an application in angular js, in which i am using ng-view for navigating templates, from routeProvider i am injecting a service called customerDetail to all templates. when i wrote a jasmine testcase for injecting customerDetail services into the CustomerReportController constructor, but i am getting
<failure type="">Error: [$injector:unpr] Unknown provider: customerDetailProvider <- customerDetail
can anyone please tell me some solution for this
main/customerReport/main.spec.js
describe('tsi', function()
{
var $scope, customerDetail;
beforeEach(module('tsi.customerReport'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
CustomerReportController = $controller('CustomerReportController', {
$scope: $scope,
customerDetail: customerDetail
});
}));
it('test CustomerReportController', inject(function() {
expect(CustomerReportController).toBeTruthy();
}));
});
main.js
angular.module( 'tsi', ['tsi.customerDetail', 'ngRoute'])
.config(function(RestangularProvider, $routeProvider)
{
RestangularProvider.setBaseUrl('/customer/service/detail');
$routeProvider.when('/customerDetail',
{
templateUrl: 'main/main.tpl.html',
controller: 'CustomerDetailController',
resolve: {
customerDetail: function(CustomerDetailService) {
return CustomerDetailService.getServiceDetail();
}
}
}).when('/customerReport',
{
templateUrl: 'main/customerReport/main.tpl.html',
controller: 'CustomerReportController',
resolve: {
customerDetail: function(CustomerDetailService) {
return CustomerDetailService.getServiceDetail();
}
}
}).otherwise(
{
redirectTo: '/customerDetail'
});
})
.factory('CustomerDetailService', function(Restangular) {
return {
getCustomerDetail: function() {
return Restangular.one('user/customerDetail').get().then(function(customerDetail) {
return customerDetail;
});
}
};
});
main/customerReport/main.js
angular.module('tsi.customerReport', [])
.controller('CustomerReportController', function($scope, $http, $filter, $timeout, customerDetail)
{
$scope.customerOrderDetails = customerDetail;
:
:
});
the same problem faced by me..
what I did was that I included all the services there in my js file. make sure all the services and providers are injected properly
here is an example code for jasmine unit testing.
describe('UserService',function() {
var scope, DataService, UserService, http, cookieStore;
beforeEach(module('app'));
beforeEach(inject(function ($http, _DataService_) {
http = $http;
DataService = _DataService_;
}));
it('getProfilePicture', function () {
http.post('/api/getProfilePicture', function (data) {
expect(data).toBeDefined();
});
});
});
DataService is my service here

How can you manually inject route resolve data inside a controller?

I have 2 routes that share a controller, one needs data resolved prior to the view loading, and the other does not need the resolved data.
Routing segment example:
...
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html'
})
...
Controller example:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
// this works for the first route, but fails for the second route with
// unknown "resolvedDataProvider"
console.log(resolvedData);
}]);
Is there any way I can get the resolvedData in the controller without explicitly using the resolve name as a dependency? So a check can be performed?
Using the $injector does not work. I would like to do something similar to:
if ($injector.has('resolveData')) {
var resolveData = $injector.get('resolveData');
}
However this does not work even for the route that has the resolveData set ('/users'):
app.controller('UsersCtrl', ['$scope', 'Helper', '$injector',
function($scope, Helper, $injector) {
// this does not work -> fails with the unknown "resolvedDataProvider" as well
$injector.get('resolvedData');
}]);
Can this be done in angularjs? Or should I just create a new controller?
Thank you.
Looks like I figured out another way to go. The resolved data is part of the $route. So you can access it using:
app.controller('UsersCtrl', ['$scope', '$route', 'Helper',
function($scope, $route, Helper) {
if ($route.current.locals.resolvedData) {
var resolvedData = $route.current.locals.resolvedData;
}
}]);
If the other route doesn't need it, just inject undefined on that route:
router:
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html',
resolve: {
resolvedData: function() {
return undefined;
}
}
})
controller:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
if(resolvedData){
//set some scope stuff for it
} else {
//do what you do when there is no resolvedData
}
}]);

AngularJS: Load templateUrl after all data received by the controller

I'd like to display my template when the data coming from my server are loaded.
I created a module called Services with inside some services to load my data, I'm using HomeService for my example.
var app = angular.module('MyApp', ['Services']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'home.html',
controller: 'Home_Ctrl',
resolve: {
loadData: //??
}
});
}]);
app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
$scope.data = HomeService.getData();
}
I guess I need to create a promise to do that. Is it possible to put this function inside my controller?
I mean, I don't want something like that:
var ctrl = app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
//Do something
}
//Promise
ctrl.fct = function($q) {
}
I want something like that:
app.controller('Home_Ctrl', ['$scope', '$q', 'HomeService', function($scope, $q, HomeService) {
//Do something
//Promise
this.fct = function() {}
}
Any idea?
Thanks.
You could use resolve property of controller.
You could create a object which will return promise and assign to controller resolve function and inject the same in controller definition kindly see very simple example
$routeProvider.when('/ExitPoll', {
templateUrl: '/partials/ExitPoll.html', controller: exitpollController, resolve: {
responseData: ['$http', function ($http) {
return $http.get('/Candidate/GetExitPolls/hissar').then(function (response) {
return response.data;
});
}],
}
});
var exitpollController = ['$scope', '$http','responseData','$rootScope',
function ($scope, $http, responseData, $rootScope) {
}];

Categories