angularJS: Error: $scope is not defined - angularjs

I want to run a service that read total unread message when user visits a few particular page. I'm using resolve for this. I set up a factory which communicates with the backend through a http call and the backend returns the count of total messages and I wanna show this in html page but all I am getting is error.
( function () {
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
console.log('this is me');
$scope.numOfNotifications =res.data.totalUnread;
});
}
angular.module('myApp', [
'ngRoute',
'myApp.login',
'myApp.home',
'myApp.directory',
'myApp.forgotpassword',
'myApp.myProfile',
])
.factory('AuthService3', ["$http", "$location", function($http, $location){
var baseUrl = 'api/';
var fetchUnreadNotifications = function()
{
return $http.post(baseUrl + 'getAllUnreadNotifications');
}
return {fetchUnreadNotifications: fetchUnreadNotifications} ;
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/components/login/loginView.html',
controllerAs: 'vm'
})
.when('/forgotpassword', {
controller: 'ForgotpasswordController',
templateUrl: 'app/components/forgotpassword/forgotpasswordView.html',
controllerAs: 'vm'
})
.when('/directory/:directoryType', {
controller: 'DirectoryController',
templateUrl: 'app/components/directory/directoryView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'app/components/home/homeView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/myprofile', {
controller: 'MyProfileController',
templateUrl: 'app/components/profile/myProfileView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
}]);
})();

The problem is that you are using $scope within the function which loads notifications. $scope will not be available there since it might not be created yet. You need to return a promise and the resolved value can be injected as a dependency to the controller.
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
deferred.resolve(res.data.totalUnread);
});
return deferred.promise;
};
And in your controllers, have a dependency for 'notifications'.
Ex: function HomeController($scope, $http, notifications){ }

Related

AngularJs routing issue using $routeProvider

My AngularJs routing always redirects to the home page and always calls HomeController rather than redirecting to /VechileRegistration/Index, VechileRegistration/VechileInward
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: '/home/home.view.html',
controllerAs: 'vm'
})
.when('/VechileRegistration/Index', {
controller: 'HomeController2',
templateUrl: '/home/home.view2.html',
controllerAs: 'vm'
})
.when('/VechileRegistration/VechileInward', {
controller: 'VehicleInwardController',
templateUrl: '/home/VehicleInward.view.html',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
How can I redirect to the right place and call the appropriate controller?
var app = angular.module('ngRoutingDemo', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/login.html',
controller: 'loginController'
}).when('/student/:username', {
templateUrl: '/student.html',
controller: 'studentController'
}).otherwise({
redirectTo: "/"
});
app.controller("loginController", function ($scope, $location) {
$scope.authenticate = function (username) {
// write authentication code here..
$location.path('/student/' + username)
};
});
app.controller("studentController", function ($scope, $routeParams) {
$scope.username = $routeParams.username;
});
});

broadcast and emit does not work with ng-router?

I want pass the value to one nerds controller to geek controller but unable to pass in ng-router.
<button type="Submit" ng-click="showUser()">Show Details</button>
.when('/geeks', {
templateUrl: 'views/geek.html',
controller: 'GeekController'
})
.when('/nerds', {
templateUrl: 'views/nerd.html',
controller: 'NerdController'
})
In Nerds controller I have this function
$scope.showUser=function(){
$rootScope.$broadcast('btnName',{message:"msg"})
}
In geek controller I receiving the value on page load itself but i am not getting the value pls help me to find the solution
$rootScope.$on('btnName',function(event,args){
$scope.msg=args.message;
console.log("$scope.message nnnn",$scope.msg)
})
The NerdController and the GeekController are in two separate pages, only one of the controllers can be active at a time, since angular has only one page open in the tab. So what I suggest is, pass the variable as a parameter to the route, you can see this in the example below.
JSFiddle Demo
JS:
var routingExample = angular.module('Example.Routing', []);
routingExample.controller('NerdController', function ($scope, $location) {
$scope.showUser = function(){
console.log("show");
$location.path('/geek/1');
}
});
routingExample.controller('GeekController', function ($scope, $routeParams) {
$scope.id = $routeParams.id;
});
routingExample.config(function ($routeProvider) {
$routeProvider.
when('/nerds', {
templateUrl: 'home.html',
controller: 'NerdController'
}).
when('/geek/:id', {
templateUrl: 'blog.html',
controller: 'GeekController'
}).
otherwise({
redirectTo: '/nerds'
});
});

AngularJS routeParam not working

I have url like this:
http://localhost:3000/details/59567bc1de7ddb2d5feff262
and I want to get the parameter id
59567bc1de7ddb2d5feff262
But for some reasons routeParam always returns undefined
My controller is:
task.controller('ctrla', function($rootScope, $scope, $http, $timeout, $routeParams){
$scope.first = 1;
console.log($routeParams);
});
routes :
task.config(function ($routeProvider, $locationProvider){
$routeProvider.when('/details/:id', {
templateUrl: "details.html",
controller: "ctrla"
})
});
any help will be a life save.
Make sure you have defined the route urls as mentioned below,
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
template: "HI this is home Screen",
controller: 'ctrla'
})
.when('/details/:id', {
templateUrl: "template.html",
controller: 'profileController'
})
.otherwise({
redirectTo: '/home'
})
}]);
DEMO
If yu have route deinition defined as
$routeProvider.when('/details/:id', {
templateUrl: "partial.html",
controller: "ctrla"
})
Then in controller you should get its value as
task.controller('ctrla', function($rootScope, $scope, $http, $timeout, $routeParams){
$scope.first = 1;
console.log($routeParams.id);
});

Error: $injector:unpr Unknown Provider when adding $uibModalInstance to controller

When I add $uibModalInstance to my controller I get the error:
Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- EventAdditionalInformationTabCtrl
My controller is defined as:
angular.module('myWebApp.controllers').
controller('EventAdditionalInformationTabCtrl', function ($scope, $uibModalInstance, eventData) {
});
I have another controller that defines the open function:
controller('modalCtrl', function ($scope, $uibModal) {
$scope.open = function (template, instance, size) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: template,
controller: instance,
size: size
});
};
}).
Then I want to pass the controller that will handle a specific instance of a modal, in this case EventAdditionalInformationTabCtrl.
My app is defined as:
var app = angular.module('myWebApp', [
'myWebApp.services',
'myWebApp.controllers',
'ui.router',
'duScroll',
'ngAnimate',
'ui.bootstrap',
'angularUtils.directives.dirPagination',
'angular-loading-bar'
]);
What am I missing?
EDIT ----
Here's how EventAdditionalInformationTabCtrl is linked to the view in ui-Router.
$stateProvider
.state('event', {
url: '/event',
params: {
eventId: null
},
resolve: {
eventData: ['$http', '$stateParams', function ($http, $stateParams) {
console.log('EventId: ' + $stateParams.eventId);
return $http.get('http://localhost:10569/api/eventView/' + $stateParams.eventId).then(function(response) {
return response.data;
});
}]
},
views: {
'': {
templateUrl: 'partials/events/event.html'
//controller: 'EventCtrl'
},
'eventHeader#event' : {
templateUrl: 'partials/events/event-header.html',
controller: 'EventHeaderCtrl'
},
'eventOverviewTab#event': {
templateUrl: 'partials/events/event-overview-tab.html',
controller: 'EventOverviewTabCtrl'
},
'eventDSOTab#event': {
templateUrl: 'partials/events/event-dso-tab.html',
controller: 'EventDSOTabCtrl'
},
'eventAdditionalInformationTab#event': {
templateUrl: 'partials/events/event-additional-information-tab.html',
controller: 'EventAdditionalInformationTabCtrl'
},
'eventFooter#event': {
templateUrl: 'partials/events/event-footer.html',
controller: 'EventFooterCtrl'
}
}
});
Where you have $uibModalInstance now should just be $uibModal. Use $uibModalInstance when you want to actually create a modal. This plunker is the official example for how to use $uibModal.
You need to inject '$uibModal' into your controller.
Check out the angular ui docs here https://angular-ui.github.io/bootstrap/#/modal
EDIT:
Change this
animation: true,
templateUrl: template,
controller: instance,
size: size
to this
animation: true,
templateUrl: template,
controller: EventAdditionalInformationTabCtrl,
size: size

spa wont redirect to login page?

I am looking at building a clientside authentication for my angular app. The routing looks like this:
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/customers', {
controller: 'CustomersController',
templateUrl: 'customers.html',
secure: true
})
.when('/login/:redirect*?', {
controller: 'LoginController',
templateUrl: 'login.html'
})
.when('/testing', {
controller: 'TestController',
templateUrl: 'testing.html' })
.otherwise({ redirectTo: '/customers' });
}]);
When I click on the login link it wont let me go to the login page?
See also this plunkr: http://plnkr.co/edit/TVSnCp8AtBKVfcYdWvN2?p=preview
Please update the app.js
(function () {
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/customers', {
controller: 'CustomersController',
templateUrl: 'customers.html',
secure: false
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'login.html'
})
.when('/testing', {
controller: 'TestController',
templateUrl: 'testing.html' })
.otherwise({ redirectTo: '/customers' });
}]);
app.run([ '$rootScope', '$location', 'authService',
function ( $rootScope, $location, authService) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (next && next.$$route && next.$$route.secure) {
if (!authService.user.isAuthenticated) {
authService.redirectToLogin();
}
}
});
}]);
}());

Resources