AngularJS Controller Access for all views - javascript

I'm currently working on an AngularJS app and attempting to create a controller with functions to be used throughout the app. Examples of this include a back button, a logout button, and navigation links. However when trying to execute it, it won't work. How would I be able to make it work.
For reference, body starts with
Below is my controller code:
angular.module('Squeeg.controllers', [])
.controller('SqueegApp', function($scope, $state, $rootScope, $stateParams) {
$scope.back = function() {
$state.go('welcome');
};
$scope.logout = function() {
Parse.User.logOut();
$rootScope.user = null;
$rootScope.isLoggedIn = false;
$state.go('welcome', {
clear: true
});
};
})
.controller('WelcomeController', function($scope, $state, $rootScope, $stateParams) {
alert("test");
})
.controller('HomeController', function($scope, $state, $rootScope) {
$scope.home = "Home";
})
.controller('View2', function($scope, $state, $rootScope) {
$scope.message = "Test";
});

Related

Cannot read propery getRiders of undefined

I want to call a service which I defined in DeliverService but when I called it from controller it gives an error of Cannot read propery getRiders of undefined , NO idea why this happened :|
DeliverService.js
angular.module('Deliver')
.service('DeliverService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService", function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getRiders : function(){
return $http.get("Hero.json");
//return $http.get(SettingService.baseUrl + "api/orders");
} }
return service;
}]);
DeliverCtrl.js
use strict';
angular.module('Deliver').controller('DeliverCtrl',['$scope','$state', "SettingService","DeliverService", function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){
});
}]);
Your dependencies aren't in the matching order here. Hence, DeliverService isn't actually injected.
Your controller code should look something like this:
angular.module('Deliver').controller('DeliverCtrl',
['$scope','$state', '$ionicModal', 'MessageService', 'SettingService','DeliverService',
function($scope, $state, $ionicModal, MessageService, SettingService, DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){});
}]);
In DeliverCtrl.js
The injection Parameter and function parameters do not match
It should be like this
['$scope','$state','$ionicModal','MessageService','SettingService','DeliverService', function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService)

Service undefined when injected into controller

I have a controller that I have injected a factory into but it comes back as undefined when I call a method on that factory. Not sure what I am doing wrong here. Any help would be appreciated.
Factory:
(function(){
'use strict';
// Declare factory and add it 'HomeAutomation' namespace.
angular.module('HomeAutomation').factory('AuthenticationService', ['$http','$localStorage', '$window', function($http, $localStorage, $window){
var service = {};
service.login = Login;
service.logout = Logout;
service.parseJWT = parseJWT;
service.loginStatus = loginStatus;
return service;
function Login(email, password, callback){
$http.post('api/user/login', {email: email, password: password})
.success(function(res){
// Login successful if there is a token in the response.
if(res.token){
// store username and token in local storage to keep user logged in between page refreshes
$localStorage.currentUser = { email: email, token: res.token };
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = 'Bearer ' + res.token;
callback(true);
}else{
callback(res);
}
}).error(function(err){
console.log(err);
});
}
function Logout(){
$localStorage.currrntUser
}
function parseJWT(token){
var base64URL, base64;
base64URL = token.split('.')[1];
base64 = base64URL.replace('-', '+').replace('_', '/');
console.log(JSON.parse($window.atob(base64)));
}
function loginStatus(){
if($localStorage.currentUser){
return true;
}else{
return false;
}
}
}]);}());
Controller:
(function(){
angular.module('HomeAutomation')
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
$scope.isLoggedIn = AuthenticationService.logout();
$scope.logUserIn = function(){
AuthenticationService.login($scope.login.email, $scope.login.password, function(result){
if(result === true){
$location.path('/');
}else{
console.log(result);
}
});
};
$scope.logUserOut = function(){
AuthenticationService.logOut();
}
}]);}());
This is the line that is causing the err:
$scope.isLoggedIn = AuthenticationService.logout();
Apparently "AuthenticationService" is undefined. Not sure why.
Thanks in advance.
You messed up with depedency sequence, you need to remove $localStorage from controller factory function since $localStorage isn't use anywhere in controller & haven't injected in DI array.
.controller('loginController', ['$scope', '$location', 'AuthenticationService',
function($scope, $location, AuthenticationService){
//^^^^^^^^^^removed $localStorage dependency from here
NOTE: Always make sure when you inject any dependency in DI array, they should used in same sequence in controller function
The injection is not good :
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
Try with this :
.controller('loginController', ['$scope', '$location', '$localStorage', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
I don't know which builder you use, but for example with Gulp, you can use gulp-ng-annotate that will do the job for you so that you can only write :
.controller('loginController', function($scope, $location, $localStorage, AuthenticationService){
without the array. The ng-annotate will take care of the rest.

$location.path same url not working

Below is my code:
app.controller('lookupMasterController', [
'$scope', '$routeParams', '$location', '$modal', 'lookupService', function ($scope, $routeParams, $location, $modal, lookupService) {
$scope.openCreatePopup = function () {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'app/popups/add-lookup.html',
controller: function ($scope, $modalInstance, $location, $routeParams, lookupService) {
$scope.cancel = function () {
$modalInstance.close();
}
$scope.addLookup = function () {
$scope.lookup.lookUpConfigId = $routeParams.lookupMasterId;
lookupService.save($scope.lookup).$promise.then(
function (value) {
$location.path('/edit-lookup/' + $routeParams.lookupMasterId);
$scope.$apply();// Even this is not working.
// Tried the below as well:
//$scope.$apply(function () {
// $location.path('/edit-lookup/' + //$routeParams.lookupMasterId);
// });
$modalInstance.close();
},
function (error) { /*Do something with error*/
alert(error.message);
});
}
},
size: 'lg'
});
}
}
]);
I am opening a Popup for add new lookup and then reloading the page to see the changes. But the problem is : $location.path('url'); is not working.
You should use $state service in that case. Try
$state.go('/edit-lookup/' + $routeParams.lookupMasterId);
Don't forget to inject $state in your controller initilization. Plus in your module definition you need to pass 'ui.router' as a dependency :
E.g. angular.module('my_app', ['ui.router'])
EDIT
I think you didn't load ui-router.min in your web page. Please load it just after angular.js
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>

AngularJS: '$scope is not defined'

I keep getting '$scope is not defined' console errors for this controller code in AngularJS:
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
}
]);
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
For others who land here from Google, you'll get this error if you forget the quotes around $scope when you're annotating the function for minification.
Error
app.controller('myCtrl', [$scope, function($scope) {
...
}]);
Happy Angular
app.controller('myCtrl', ['$scope', function($scope) {
...
}]);
Place that code inside controller:-
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
}
]);
Just put you $scope.create function inside your controller. Not outside !
$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.
Check scope variable declared after controller defined.
Eg:
var app = angular.module('myApp','');
app.controller('customersCtrl', function($scope, $http) {
//define scope variable here.
});
Check defined range of controller in view page.
Eg:
<div ng-controller="mycontroller">
//scope variable used inside these blocks
<div>

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();
}])

Categories