AngularJS constants undefined is not an object - javascript

new to Angular and I'm trying to inject constants from a separate file. It seems to work with the DI, but when I try to use it, I get an error: Error: undefined is not an object (evaluating 'CApiEndpoints.authUrl').
I tried dot notation and brackets as suggested in Accessing AngularJS constants but continue to get the error.
The files are included in index.html, and DI doesn't complain.
index.html
<script type="text/javascript" src="js/angular/constants.js"></script>
<script type="text/javascript" src="js/angular/app.js"></script>
js/angular/constants.js
var app = angular.module('appConst', []);
app.constant('CApiEndpoints', {
authUrl: 'http://api.example.com/v1/',
...
});
and my js/angular/app.js
var app = angular.module('app', ['ngRoute', 'ngCookies', 'appConst', 'appServices']);
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints', function($scope, $route, $http, $cookies, $routeParams, $location, CApiEndpoints){
console.log(CApiEndpoints); // shows 'undefined'
$http({
method : 'GET',
url : CApiEndpoints.authUrl + 'user_info'
})
.then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
});
}]);
Any help would be appreciated. I've searched for the last 2 hours trying to figure this out.

While injecting dependencies inside your controller function using DI inline array annotation, they must follow the order how they are injected in array.
If you follow above rule you will come to know that you have two extra paramters inside your function, so you should remove those two unwanted ($routeParams, $location) dependency.
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints',
function($scope, $route, $http, $cookies, CApiEndpoints){
//controller code
}
]);
If you haven't added those parameter mistakenly, you should add those parameter on both side inside function & array.
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', '$routeParams', '$location', 'CApiEndpoints',
function($scope, $route, $http, $cookies, $routeParams, $location CApiEndpoints){
//controller code
}
]);

Related

$cookies.get is not a function - Angular JS

Designed two pages. Cookies is not set and showing error.
CDN:
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-cookies.js"></script>
Main Page - Set Cookies / cookies is not set
var app = angular.module('myApp', ['ngCookies']);
app.controller('LoginCtrl', ['$cookies', '$scope', '$http', '$window', '$location', function($cookies,$scope, $http, $window, $location) {
$cookies.put('username', 'name');
}
Second Page - Get Cookies
var app = angular.module('myApp', [ 'ngTable', 'ngCookies' , 'ngResource']);
app.controller('AccountMappingCtrl', ['$scope', '$http','$cookies', 'NgTableParams', function($scope, $http, $filter, $cookies, NgTableParams) {
$scope.UsernameCookies = $cookies.get("username");
}
It is showing $cookies.get is not working.
try following
$scope.UsernameCookies = $cookies[username];
if will not work inject '$cookieStore' in your controller and try following:
$cookieStore.get('username')

AngularJS Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got undefined

Trying to run an Angular app containing this controller:
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
, function($scope, $timeout) { /* body omitted */ }
gives me the error:
Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got undefined
What am I doing wrong?
The actual problem is that I had an extra , in the controller. When I changed that, it worked.
From
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
, function($scope, $timeout) {
To
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
function($scope, $timeout) {

AngularJS: Having trouble restructuring

Here is the current (Working) way i have my angular app.
app.js
require('angular');
require('angular-ui-router');
var listStoresCtrl = require('./controllers/store/listStoresCtrl');
var createStoreCtrl = require('./controllers/store/createStoreCtrl.js');
var storeDetailsCtrl = require('./controllers/store/storeDetailsCtrl.js');
var listDepartmentsCtrl = require('./controllers/dept/listDepartmentsCtrl');
var createDepartmentCtrl = require('./controllers/dept/createDepartmentCtrl.js');
//-- init angular js
var ngApp = angular.module('ngApp', ['ui.router'], function($interpolateProvider){
//-- as the output conflicts with blade lets alter the defaults
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}).config(['$stateProvider','$logProvider','$urlRouterProvider', function ($stateProvider, $logProvider,$urlRouterProvider) {
//-- enable logging
$logProvider.debugEnabled(true);
}]);
ngApp.controller('listStoresCtrl', ['$scope', 'Store', '$log', listStoresCtrl]);
ngApp.controller('createStoreCtrl', ['$scope', '$log', 'Store', '$rootScope', '$timeout','ManagerService', createStoreCtrl]);
ngApp.controller('storeDetailsCtrl', ['$scope', '$log', '$rootScope', 'Store', storeDetailsCtrl]);
ngApp.controller('listDepartmentsCtrl', ['$scope', 'Department', '$log', listDepartmentsCtrl]);
ngApp.controller('createDepartmentCtrl', ['$scope', '$log', 'Department', '$rootScope', '$timeout','ManagerService', createDepartmentCtrl]);
//-- stick it all together and kick it off
angular.bootstrap(document, ['ngApp']);
BUT i would like to restructure this so that my Store ctrls etc and Department ctrls are within their own module.
EG: storeCtrls.js
angular.module('storeCtrls', [])
.controller('listStoresCtrl', ['$scope', 'Store', '$log', listStoresCtrl])
.controller('createStoreCtrl', ['$scope', '$log', 'Store', '$rootScope', '$timeout','ManagerService', createStoreCtrl])
.controller('storeDetailsCtrl', ['$scope', '$log', '$rootScope', 'Store', storeDetailsCtrl]);
Then in the app.js file call them in like so.
require('./controllers/storeCtrls');
angular.module('ngApp', ['storeCtrls'], function($interpolateProvider){...}
But for some reason this does not work I am get getting an error of Uncaught object.
Bit of relevant history on this:
I am using Gulp and Browserify to do my JS.
My listStoresCtrl for example are using the
module.exports = function(scope, Store, log){...}
method to return them.
UPDATE
i seem to have sorted the Uncaught object, as i was missing the ['ui.router'] with the call to
angular.module('ngApp', ['storeCtrls']...
so it should be
angular.module('ngApp', ['ui.router', 'storeCtrls']..
Now to get the rest to link up...
Seems the main issue was i was not injecting some items that i simply removed and forgot to re-add.
I simply must of copied over this injection ['ui.router'] with the call to
angular.module('ngApp', ['storeCtrls']...
where i should have been adding as well below:
angular.module('ngApp', ['ui.router', 'storeCtrls']..
Now to get the rest to link up...

Using Angular services to hold commonly required data

I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])

Unknown scope provider $scope

I am trying to inject $scope but it's not working. This is my code:
var appCtrl = app.controller(
'AppCtrl',
function ($scope, $resource, $location, $route, sharedProperties) {}
);
appCtrl.prepData = function (
$q, $scope, $resource, $location, $route, sharedProperties) {}
I am trying to define a function after getting the appCtrl variable. But $scope wouldn't work there. Any idea how to resolve this issue?

Categories