routes.js
angular
.module('main')
.config(config);
config.$inject = ['$routeProvider', '$httpProvider'];
function config($routeProvider){
$routeProvider
.when('/', {
templateUrl:'main/views/landing.client.view.html',
controller:'MainController',
controllerAs:'mainCtrl',
resolve: {
orgTypes: orgTypes
}
})
.otherwise({
redirectTo:'/'
});
}
function orgTypes($http){
return $http
.get('emrsvs/orgTypes')
.then(function successCallBack(response){
return response;
}, function errorCallBack(error){
console.log(error);
});
}
controller.js
angular
.module('main')
.controller('MainController', MainController);
MainController.$inject = ['$rootScope', '$timeout', 'orgTypes'];
function MainController($rootScope, $timeout, orgTypes){
var mainCtrl = this;
mainCtrl.orgTypes = orgTypes;
}
Error
[$injector:unpr] Unknown provider: orgTypesProvider <- orgTypes <- MainController
Here i am injecting a dependency 'orgTypes' from route to controller. It produced unknown provider error. Is there anything wrong with my sysntax? can someone find my mistake
you should include following code in routes.js , before orgTypes function definition
angular.module('main')
.factory('orgTypes', orgTypes);
orgTypes.$inject = ['$http'];
/*You need to apply following changes also in controller*/
angular
.module('main')
.controller('MainController', MainController);
MainController.$inject = ['$rootScope', '$timeout', 'orgTypes'];
function MainController($rootScope, $timeout, orgTypes){
var mainCtrl = this;
orgTypes.then(function(response){
mainCtrl.orgTypes = response;
})
}
I can't see anything wrong if you inject the controller with the ng-view directive.
<div ng-app="main">
<ng-view></ng-view>
</div>
Your code works in this JSFiddle.
In your router config, you inject orgTypes from a resolver function. The $routeProvider service injects resolvers as locals into controllers. That method works OK.
If you use the ng-controller directive to load MainController, you will get that error. The $compile service doesn't have access to those resolvers in that case.
Related
I'm having a problem trying to inject $ http to the factory. I miss the following error in Angular 1.6:
Circular dependency found: $rootScope <- $http <- $exceptionHandler <- $rootScope <- $route
And this was what I was doing so far:
var app = angular.module("app", []);
app
.controller("ctrl", function($scope) {
// controller
})
.factory('$exceptionHandler', ['$log', '$http', function($log, $http) {
return function myExceptionHandler(exception, cause) {
$log.warn(exception, cause);
// I show only this and it already throws error
console.log($http);
}
}]);
To work around the circular dependency, try the following.
Instead of injecting $http directly into the interceptor try injecting the $injector and use that directly to get $http.
var app = angular.module("app", []);
app.factory('$exceptionHandler', ['$log', '$injector', function($log, $injector) {
return function myExceptionHandler(exception, cause) {
var $http = $injector.get('$http');
$log.warn(exception, cause);
// I show only this and it already throws error
console.log($http);
}
}]);
I am trying to pass variable to angular js config,
This is my js app:
var app = angular.module('myApp', ['ngMaterial', 'sasrio.angular-material-sidenav', 'ui.router']);
app.controller('baseController', function ($scope, $mdDialog, $mdMedia, $http, $rootScope, $timeout, $mdToast, $mdSidenav, ssSideNav) {
$scope.menu = ssSideNav;
$scope.getRequirment = function () {
$http.get("site/requirment",
{params: {dir: $scope.currentPath}})
.then(function (response) {
return response.data;
});
};
$scope.getRequirment();
});
app.config(['$mdThemingProvider', '$locationProvider', 'ssSideNavSectionsProvider', '$stateProvider',
function ($mdThemingProvider, $locationProvider, ssSideNavSectionsProvider, $stateProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('deep-orange')
.accentPalette('deep-orange');
ssSideNavSectionsProvider.initWithTheme($mdThemingProvider);
ssSideNavSectionsProvider.initWithSections("Get getRequirment function in controller");
}]);
How can I call a function in the controller from config?
I mean this line:
ssSideNavSectionsProvider.initWithSections("Get getRequirment function in controller");
There is a durty way to do this:
you can put this in your config
$rootScope.$watch("variable", function(n, o) {
// assign n value
})
and in your controller just set the
$rootScope.variable
It's impossible, controller executes in run phase, config in config phase.
I investigate source code a little, sections available as a service variable, you could try to add them from controller:
ssSideNavSections.sections.push(yourSection);
You can set constant in configuration block and then access that constant via injecting it into controller.
Source: https://www.agiliq.com/blog/2017/04/what-when-and-how-angularjs-configuration-blocks/
I'm writing routing logic using ngRoute of angular JS. The following is my code.
index.js
(function() {
'use strict';
function config($routeProvider, $httpProvider, cfpLoadingBarProvider, $tooltipProvider) {
$routeProvider.otherwise({redirectTo: '/404'});
$httpProvider.defaults.withCredentials = false;
$httpProvider.defaults.headers.common['content-type'] = "application/json";
}
angular
.module('pacman', ['ngCookies', 'ngRoute', 'ui.bootstrap', 'ui.validate',
'angular-cache', 'angular-loading-bar', 'angular-md5', 'rt.iso8601', 'ngAnimate']
)
.config(['$routeProvider', '$httpProvider', 'cfpLoadingBarProvider', '$tooltipProvider', config])
.run(['$rootScope', '$location', '$modalStack', '$cookies']);
})();
app.controller.js
(function() {
'use strict';
function config($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'app/components/landingpage/landingpage.html',
controller: 'appController'
});
}
function appController($scope, $rootScope, $location) {
$scope.submitLogin = function() {
alert("Successfully loggedIn");
};
}
angular
.module('pacman')
.controller('appController', ['$scope', '$rootScope', '$location', appController])
.config(['$routeProvider', config]);
})();
notFound.controller.js
(function() {
'use strict';
function config($routeProvider) {
$routeProvider.when('/404', {
templateUrl: 'app/components/notFound/404page.html',
controller: 'notFoundController'
});
}
function notFoundController($scope, $rootScope, $location) {
debugger;
}
angular
.module('pacman')
.controller('notFoundController', ['$scope', '$rootScope', '$location', notFoundController])
.config(['$routeProvider', config]);
})();
My code is a simple app. I'm trying to load different controllers based on routes. However at the time of loading the app, in the last controller's '$routeProvider' it throws an error
Uncaught Error: [ng:areq] Argument 'fn' is not a function, got string
http://errors.angularjs.org/1.4.8/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20string
I have no clue how to figure out the problem. Any leads would be appreciated.
The following is my library bundle order.
'node_modules/jquery/dist/jquery.js',
'node_modules/angular/angular.js',
'node_modules/angular-route/angular-route.js',
'node_modules/jquery.transit/jquery.transit.js',
'node_modules/angular-cache/dist/angular-cache.js',
'node_modules/angular-cookies/angular-cookies.js',
'node_modules/angular-loading-bar/build/loading-bar.js',
'node_modules/angular-ui-validate/dist/validate.js',
'node_modules/chart.js/Chart.js',
'node_modules/angular-md5/angular-md5.js',
'node_modules/angular-iso8601/dist/angular-iso8601.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-chart.js/dist/angular-chart.js',
'node_modules/rx/dist/rx.all.js',
'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js',
'node_modules/bootstrap/dist/js/bootstrap.js'
Kindly help.
Issue is in your index.js where you define the run method on your angular app.
angular
.module('pacman', []) // removed dependencies for brevity
.run(['$rootScope', '$location', '$modalStack', '$cookies']);
The last argument in the array passed to run should be a function but you forgot to pass a function. Change your run to add some implementation like below or remove the run if you don't see any use for it.
angular.module('pacman', []) // removed dependencies for brevity
.run(['$rootScope', '$location', '$modalStack', '$cookies',
function($rootScope,$location,$modalStack,$cookies){
// some statements here
}]);
Angular JS file declaration must come before the jquery in your index.html
'node_modules/angular/angular.js',
'node_modules/jquery/dist/jquery.js',
I'm injecting controller from external file and I want to do the same thing for the service from external file. It should be registered in factory statement.
Injecting of the controller working
controllers
'use strict';
define(['angular', 'services'], function (angular) {
return angular.module('vcApp.controllers', ['vcApp.services'])
.controller('AuthCtrl', ['$scope', '$injector','AuthService', function($scope, $injector, AuthService) {
require(['auth/authCtrl'], function(authCtrl) {
$injector.invoke(authCtrl, this, {'$scope': $scope, 'AuthService':AuthService});
});
}]);
});
authCtrl
define([], function() {
return ['$scope', '$routeParams', '$location', '$http', 'AuthService', function($scope, $routeParams, $location, $http, authService) {
$scope.signIn = function() {
...
}
$scope.$apply();
}];
});
And now I want to inject service
services
'use strict';
define(['angular'], function (angular) {
angular.module('vcApp.services', [])
.factory('AuthService', ['$http', '$injector', function($http, $injector) {
require(['auth/authService'], function(authService) {
$injector.invoke(authService, this, {'$http': $http});
});
}]);
});
authService
define([], function() {
return ['$http', function ($http) {
return {
login: login
};
function login(username, password) {
var request = $http(...);
return(request);
}
}]
});
When authController calls authService.login(...), it throws error Error: [$injector:undef] Provider 'AuthService' must return a value from $get factory method..
This code was inspired by angular-requirejs-seed project.
As it says, Angular's factory() is expected to return the service object. You may have luck with something like:
define(['angular'], function (angular) {
angular.module('vcApp.services', [])
.factory('AuthService', ['$http', '$injector', function($http, $injector) {
var stub = {};
require(['auth/authService'], function(authService) {
angular.extend(stub, $injector.invoke(authService, this, {'$http': $http}));
});
return stub;
}]);
});
Here you define a stub for the service and extend it, when the service is actually lazy-loaded.
(By the way I think the last 2 arguments of $injector.invoke() are redundant in this case.)
If you want another idea about mixing RequireJS and Angular, that plays well with lazy loading and the r.js optimizer, you may take a look at angular-require-lazy.
I'm trying to configure my route in such a way to redirect to the login page if user is not logged. This is my code:
angular.module('witBiz.services', []);
angular.module('witBiz.controllers', ['witBiz.services']);
var witBizModule = angular.module('witBiz', ['ngRoute' , 'witBiz.controllers', 'witBiz.services' ]);
witBizModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'resources/views/login.html', controller: 'LoginController'});
$routeProvider.when('/index', {templateUrl: 'resources/views/index.html', controller: 'IndexController'});
$routeProvider.otherwise({redirectTo: 'resources/views/index.html'});
}])
.run(['$rootScope', 'checkLogin', function($rootScope, checkLogin ,$routeProvider ) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/index");
})
}])
.factory('checkLogin', function(){
return function() {
//perform real logic here
return true;
}
})
where basically I declare modules and services. Now the problem is $location is not defined so I get error.
I tried to inject $location as dependency like this but I got undefined injection (injpt):
.run(['$rootScope', 'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/ciao");
})
}])
So I'm wondering how I can use the builtin $location services inside my "run" method...why can I inject it as a dependency as $rootScope or checkLogin?!
I'm using angular 1.2.0 rc2.
Thanks
Here is a working example http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview
Couldn't reproduce the error with $location not working inside .run