$on don't catch $broadcast - javascript

I have a Angular Project and I want create Authentication mechanism so i have the following controller:
angular.module('authModule')
.controller('LoginCtrl', function($rootScope, $location, loginRESTService, UserService){
var login = this;
function signIn(user) {
loginRESTService.login(user)
.then(function(response) {
console.log(response);
user.access_token = response.user_id;
UserService.setCurrentUser(user);
$rootScope.$broadcast('authorized');
$location.path("/formList");
});
}
})
additional I have a main controller with the following methods
angular.module('authModule')
.controller('MainCtrl', function ($rootScope, $state, LoginService, UserService) {
var main = this;
$rootScope.$on('authorized', function() {
console.log("ENTRE CON PERMISO");
main.currentUser = UserService.getCurrentUser();
});
$rootScope.$on('unauthorized', function() {
console.log("ENTRE SIN PERMISO");
main.currentUser = UserService.setCurrentUser(null);
$state.go('login');
});
})
the problem it's that 'authorized' and 'unauthorized' never was invoked and don't have idea why
my app.js file
angular
.module('pysFormWebApp', [
...
'translateModule',
'formModule',
'authModule'
])
.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/login', {
templateUrl: 'views/auth/login.html',
controller: 'LoginCtrl',
controllerAs: 'login'
})
.otherwise({
redirectTo: '/'
});
my index.html (only a part because is so long and is the index that generate yo angular)
<div ng-controller="MainCtrl as main" >
<button ng-if="main.currentUser" class="btn btn-default navbar-btn" ng-click="main.logout()">Logout <strong>{{main.currentUser.name}}</strong>
</button>
</div>

First, you are not broadcasting the 'unauthorized' event. because of that the $rootScope.on('unauthorized') is not working.
Second. Maybe are running the main controller before the login controller, and because of that your controller doesn't catch the event.
let me know if it solves your problem.

Related

AngularJS $http.get with ngRoute how to list details

Maybe someone will help me. I write an app in angularjs, I have a file named list.html which retrieves a list of posts from jsonplaceholder and lists them, with a link to the details of the post. In $ routeParams, I pass the id of the selected one and pick it up. Unfortunately, I have no idea how to download the details of a post and display them in the details.html file. If I want to remove something for example, I write for example $ scope.deletePost as a function and give an id, but how to list details I have no idea.
//routing.js
var myApp = angular.module('myApp', ["ngRoute"])
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/event/example.html',
controller: 'exampleController'
}, null)
.when('/list', {
templateUrl: '/event/list.html',
controller: 'exampleController'
}, null)
.when('/test-list', {
templateUrl: '/test/list.html',
controller: 'testController'
}, null)
.when('/test/:id', {
templateUrl: '/test/details.html',
controller: 'testController'
}, null)
}
]);
//controller.js
angular.module('myApp').controller('testController', function ($scope, $http, $routeParams) {
$http.get('https://jsonplaceholder.typicode.com/posts').then(function (response) {
$scope.posts = response.data;
});
$scope.id = $routeParams.id;
});
//details.html
<div data-ng-controller="testController">
{{data}}
</div>
//list.html
<div data-ng-controller="testController">
<ul>
<li ng-repeat="post in posts">
Tytuł: {{post.title}} <a href="#!test/{{post.id}}" >Show</a>
</li>
</ul>
</div>
Check out this plunkr.
You just need to pass the details using ng-href and then catch in the controller using $routeParams. I hope this would help you with what you were looking for.
var app = angular.module( 'mainApp', ['ngRoute'] );
app.config( function( $routeProvider ) {
$routeProvider
.when( '/main', {
templateUrl: 'list.html',
controller: 'listCtrl'
})
.when('/detail/:id', {
templateUrl: 'detail.html',
controller: 'detailCtrl'
})
.otherwise({
redirectTo: '/main'
});
});
app.controller( 'listCtrl', function( $scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(res){
$scope.data = res.data;
})
});
app.controller( 'detailCtrl', function( $scope,$http, $routeParams) {
$scope.id = $routeParams.id;
$http.get('https://jsonplaceholder.typicode.com/posts/'+$scope.id)
.then(function(res){
$scope.data = res.data;
})
});

Angularfire ngRoute/resolve issue, jumps to otherwise

I'm using the latest Angular + Firebase and trying to set up a login authorization system. I have home.html which contains login+signup links, going to login.html and adding credentials works just fine (logging correct UID when submittet) but it's supposed to route to dash.html but goes back to home.html.
I've figured out that it seem to be issues with my resolve functions because the problem disappears when I remove .otherwise. But I still want (need?) it there I think.
If I'm logged in (but redirected to home.html) I can still access dash.html through the URL and I cannot access it again if I use the logout function at dash.html and that's how it should be.
But I can't figure out why I'm redirected to home.html in the first place.
Here's some of the code, any help appreciated:
My .run, .config and routes.
app.run(['$rootScope', '$location',
function($rootScope, $location){
$rootScope.$on('$routeChangeError',
function(event, next, previous, error){
if(error === 'AUTH_REQUIRED'){
$location.path('/home');
}
});
}]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider,
$locationProvider){
$routeProvider
.when('/home', {
templateUrl: '/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: '/login.html',
controller: 'loginController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$waitForAuth();
}]
}
})
.when('/dash', {
templateUrl: '/dash.html',
controller: 'dashController',
resolve: {
'currentAuth': ['Auth', function(Auth){
return Auth.$requireAuth();
}]
}
})
.otherwise({ redirectTo: '/home' });
}]);
My login controller:
app.controller('loginController', ['currentAuth', '$scope', '$firebaseAuth',
'Auth', '$location', '$rootScope',
function(currentAuth, $scope, $firebaseAuth, Auth, $location, $rootScope){
var ref = new Firebase('https://url.firebaseio.com');
$scope.auth = $firebaseAuth(ref);
$scope.loginUser = function(){
$scope.auth = Auth;
$scope.auth.$authWithPassword({
email:$scope.email,
password:$scope.password
}, {
remember: 'sessionOnly'
}).then(function(authData) {
console.log('Logged in as: ', authData.uid);
$scope.auth.$onAuth(function(authData) {
$rootScope.auth = true;
$scope.auth = Auth;
$location.path('/dash.html');
})
}).catch(function(error) {
console.log('There was an error: ', error);
});
};
}]);
And my factory and module:
var app = angular.module('app', ['firebase', 'ngRoute']);
app.factory('Auth', ['$firebaseAuth',
function($firebaseAuth){
var ref = new Firebase('https://url.firebaseio.com');
return $firebaseAuth(ref);
}]);
it has with your resolve issue.
If you look at the documentation firebase doc
you will see that they use the
$waitForSignIn
or
$requireSignIn
functions. I know that because I have done the same thing. Try that instead and it should work

Angularjs routing without hash with multiple var

Yo everyone.
I searched how to remove the hash(#) from the routing (source: AngularJS routing without the hash '#') but I encountered a problem.
I'll explain.
$locationProvider.html5Mode(true);
$routeProvider
.when('/test', {
controller: TestCtrl,
templateUrl: 'test.html'
})
.when ('/test/:idPage', {
controller: PageCtrl,
templateUrl: 'page.html'
})
.otherwise({ redirectTo: '/test' });
For the first redirection
- I've got something like : www.my-website.com/test
all is working fine.
For the second :
- www.my-website.com/test/hello
and here, there is a prob, when I put more than one " / " in the route, no page is loaded and I've got two
Failed to load resource: the server responded with a status of 404
(Not Found)
in my console.
One called : www.my-website.com/test/page.html and the other : www.my-website.com/test/hello
Hope someone can help me. Thanks in advance.
Angular 1.4.x requires that 'ngRoute' be included in the module to use $routeProvider and $locationProvider so include it as a <script...>:
angular-router (see here).
I am assuming you see something like:
To include it in your module:
var app = angular.module('someModule', ['ngRoute']);
And the controller needs to be in quotes controller: 'someCtrl' like:
$locationProvider.html5Mode(true);
$routeProvider
.when('/test', {
controller: 'TestCtrl',
templateUrl: 'test.html'
})
.when ('/test/:idPage', {
controller: 'PageCtrl',
templateUrl: 'page.html'
})
.otherwise({ redirectTo: '/test' });
Here is an example that I put together: http://plnkr.co/edit/wyFNoh?p=preview
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/hello/:idHere', {
templateUrl: 'resolveView.html',
controller: 'helloCtrl',
resolve: {
exclamVal: function(){
return '!!!!!!!!!!'
}
}
})
.when('/default', {
templateUrl: 'default.html',
controller: 'defaultCtrl'
})
.when('/test', {
controller: 'testCtrl',
templateUrl: 'test.html'
})
.otherwise({ redirectTo: '/default' });
$locationProvider.html5Mode(true);
}]);
app.controller('MainCtrl', function($scope, $location, $routeParams) {
});
app.controller('testCtrl', function($scope, $routeParams) {
console.log('hi')
});
app.controller('defaultCtrl', function($scope, $routeParams) {
console.log('Inside defaultCtrl')
});
app.controller('helloCtrl', function($scope, exclamVal, $routeParams) {
$scope.exclamVal = exclamVal;
$scope.myVar = $routeParams.idHere;
});

$state.go not working - Error : $state isnot defined

Hi im Very new Angulay js Ionic development. im trying to basic navigation when button is clicked. but im getting this error when i click the button in Firebug console . i want to navigate to the search page after it clicked
Error : $state isnot defined
Here my App.js Code
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('signin', {
url: "/sign-in",
templateUrl: "templates/sign-in.html",
controller: 'AppCtrl'
})
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.search', {
url: "/search",
views: {
'menuContent': {
templateUrl: "templates/search.html"
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/sign-in');
});
here my Controller
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicPopup, $timeout, $ionicModal) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
})
My HTML button is
<button class="button button-block button-positive" id="login-btn" ng-click="signIn(user)" type="submit">Log in</button>
You should also get in the habit of properly injecting your dependencies. It should look like this (including the $state injection):
.controller('AppCtrl',['$scope', '$ionicPopup', '$timeout', '$ionicModal', '$state', function($scope, $ionicPopup, $timeout, $ionicModal, $state) {
$scope.signIn = function(user) {
//console.log('Sign-In', user);
$state.go('app.search');
};
}])
Just make sure the order of injections in the quotes are in the same order as the order of your parameters in the following function.

Using HTML5 pushstate on angular.js

I am trying to implement html5's pushstate instead of the # navigation used by Angularjs. I have tried searching google for an answer and also tried the angular irc chat room with no luck yet.
This is my controllers.js:
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
}
function PhoneDetailCtrl($scope, $routeParams) {
$scope.phoneId = $routeParams.phoneId;
}
function greetCntr($scope, $window) {
$scope.greet = function() {
$("#modal").slideDown();
}
}
app.js
angular.module('phoneapp', []).
config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: PhoneListCtrl
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl
}).
otherwise({
redirectTo: '/phones'
});
}])
Inject $locationProvider into your config, and set $locationProvider.html5Mode(true).
http://docs.angularjs.org/api/ng.$locationProvider
Simple example:
JS:
myApp.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/page1', { template: 'page1.html', controller: 'Page1Ctrl' })
.when('/page2', { template: 'page2.html', controller: 'Page2Ctrl' })
});
HTML:
Page 1 | Page 2

Categories

Resources