I'm using angular 1.5.0-beta2
i want to be able to read the parameter /cocktail/:cocktail_name
here i define the app and controller:
var app = angular.module('myalcoholist',['ngMaterial','ngRoute']);
app.controller('CocktailController',['$scope','$http', function ($scope,$http) {
$scope.cocktailStepsRows=null;
$http({
method: 'GET',
url: 'http://api.myalcoholist.com:8888/cocktail/steps/' + $scope.cocktail_name
}).then(function successCallback(response) {
$scope.cocktailStepsRows=response.data;
}, function errorCallback(response) {
alert('error');
});
}]);
as you can see i'm trying to append to the api url $scope.cocktail_name
this is how i configure ng-view:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/',{
templateUrl: 'views/index.html',
controller: 'IndexController'
}).
when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController'
}).
when('/cocktail/:cocktail_name', {
templateUrl: 'views/cocktail.html',
controller: 'CocktailController'
}).
otherwise({
redirectTo: '/'
});
}]);
as you can see i configured the route properly to receive the cocktail_name parameter.
now the problem i'm having is that in the controller, $scope.cocktail_name is undefined.
in the view when i print cocktail name
{{cocktail_name}}
I receive the parameter properly. why not in the controller?
what am I missing?
You did not copy the parameter value to the scope. Fix it using:
$scope.cocktail_name = $routeParams.cocktail_name
Related
I have the following routing:
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
when('/paneluser', {
templateUrl: 'views/panelUser.html',
controller: 'userCtrl'
}).
when('/paneluserblocks', {
templateUrl: 'views/userPanels.html',
controller: 'userCtrl'
}).
when('/registred', {
templateUrl: 'views/registredPanels.html'
}).
when('/color', {
templateUrl: 'views/color.html',
controller: 'alarmCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
When I specify a controller for a particular html template, my $scope variables are no longer updated in the view.
When I pull out the controller specification for a particular route, things return to normal.
The controller 'userCtrl' is accessed through $location and is intended for ordinary users. In turn, 'Ctrl panel' is the primary controller assigned to admin users.
Could anyone tell me what's going on?
I haven't all information, but it's working in my demo.
Config
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
Definition of your controller:
app.controller('painelCtrl',painelCtrl);
painelCtrl.$inject = ['$scope'] //and more if you need $http, services, ...
function painelCtrl($scope){
$scope.hello= "hello world"
}
HTML
<h1>{{hello}}</h1>
I'm sorry for the igenuidade. I believed that the pages being in the same controller, I would never miss the reference:
When ('/panel', {
TemplateUrl: 'views/panel.html',
Controller: 'panelCtrl'
}).
When ('/make', {
TemplateUrl: 'views/makePanel.html',
Controller: 'panelCtrl'
}). cotinue...
In fact, views panel.html and makePanel.html will use the same controller structure, however we will have one instance for each view (variables will be reseted).
In my case I used factory functions to solve the problem. Every time I mute controller, I store the information of interest through a set () and get it through a get ();
app.factory("MonitorService", function () {
var info;
function set(data) {
info = data;
}
function get() {
return info;
}
return {
set: set,
get: get
}
});
This is the third time this week that I reach some one code that user an AppController like this in it app
<body ng-app="app" ng-controller="AppCtrl">
<div id="inner" ng-view="" ></div>
</body>
And in the controller they redirect to the different parts of the app,
like this
.controller("AppController",function({$location}{
if(isUserAthenticated){
$location.path("/home");
}else{
$location.path("/login")
}
});
Is this the correct way to do this. Because it doesn't seem to me. I see this approach very hacky and there should be a right way to do it.
Can you guys let me know the best and recommended way to handle this kind of scenarios?
UPDATE: Routing config
// delete $httpProvider.defaults.headers.common["Access-Control-Request-Headers"];
$routeProvider
.when('/app', {
templateUrl: 'views/login.html',
controller: 'AppCtrl'
}).
when('/privados', {
templateUrl: 'views/privados.html',
controller: 'PrivadosCtrl as ctrl'
}).
when('/mensaje/:id', {
templateUrl: 'views/mensaje.html',
controller: 'MensajeCtrl as ctrl'
}).
when('/grupales', {
templateUrl: 'views/grupales.html',
controller: 'GrupalesCtrl as ctrl'
}).
when('/comunicados', {
templateUrl: 'views/comunicados.html',
controller: 'ComunicadosCtrl as ctrl'
}).
when('/contactos', {
templateUrl: 'views/contactos.html',
controller: 'ContactosCtrl'
}).
when('/perfil', {
templateUrl: 'views/perfil.html',
controller: 'PerfilCtrl'
}).
when('/principal', {
templateUrl: 'views/principal.html',
controller: 'PrincipalCtrl as ctrl'
}).
when('/nmensaje/:type', {
templateUrl: 'views/nmensaje.html',
controller: 'NMensajeCtrl as ctrl'
}).
when("/user/password",{
templateUrl:"views/passwordreset.html",
controller: "ResetPasswordCtrl as ctrl"
}).
otherwise({
redirectTo: '/app'
});
The best way that I found to manage the Authentication in an Angular App is the following:
Inside the .config() method of your Angular App:
//this event will be fired in every location change.
$rootScope.$on('$routeChangeSuccess', function(e, toState, fromState) {
if (toState.loginRequired) {
if (!isUserAthenticated()) {
e.preventDefault();
$location.path('/login');
}
}
});
then in your routes you could specify which one required the login:
when('/nmensaje/:type', {
templateUrl: 'views/nmensaje.html',
controller: 'NMensajeCtrl as ctrl',
loginRequired: true
}).
when("/user/password",{
templateUrl:"views/passwordreset.html",
controller: "ResetPasswordCtrl as ctrl",
loginRequired: true
}).
Furthermore you can create an Angular Factory to manage the authentication status of the user.
Note that with this approach you wont need an AppCtrl.
I have been trying to navigate to views using angulateJs ngRoute.
I defined first navigation using
$routeProvider.
when('/login', {
templateUrl: 'login.html',
controller: 'loginCtrl'
}).
when('/home', {
templateUrl: 'home.html'
}).
otherwise({
redirectTo: '/login'
});
Now I want to move to page home from loginController. How can I achieve that. every post just saying about navigating from main page only.
I tried with
app.controller('loginCtrl', function($scope, $location){
$scope.login = function(){
$location.path('/home');
}
});
Binod you should probably look in to the $state injector on the controller. This $state will have states to which you can reach, which are internally mapped to some other templates, like $state.go('someOtherPage').
I would suggest you to checkout $stateProvider
Inject $location in your code where u want to go to the template, and then use $location.path('/home');
try
when('/home',{
templateUrl : 'home.html',
controller : 'HomeController'
})
and create one empty controller with the name HomeController.
Solved using $stateProvider.
var routerApp = angular.module('starter', ['ui.router','']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'login.html',
controller: 'loginCtrl'
})
.state('home', {
url: '/homeffgfg',
templateUrl: 'home.html'
});
});
and Login Controller is
app.controller('loginCtrl', function($scope, $state){
$scope.login = function(){
$state.go('home');
}
});
ui.router dependency is important and <script type="text/javascript" src="js/angular-ui-router.js"></script>
I am using routesegment provider for routing in angular. how can i make a url call using $location.path().
Code is below :
FinancialGameApp.config(['$routeSegmentProvider', '$routeProvider', function ($routeSegmentProvider, $routeProvider) {
// Configuring provider options
$routeSegmentProvider.options.autoLoadTemplates = true;
// Setting routes. This consists of two parts:
// 1. `when` is similar to vanilla $route `when` but takes segment name instead of params hash
// 2. traversing through segment tree to set it up
$routeSegmentProvider
.when('/Home', 's1')
.when('/Login', 's2')
.when('/Signup', 's3')
.when('/UserDetails', 's4')
.segment('s1', {
templateUrl: 'Views/home.html',
controller: 'loginController'
})
.segment('s2', {
templateUrl: 'Views/login.html',
controller: 'loginController'
})
.segment('s3', {
templateUrl: 'Views/signup.html',
controller: 'loginController'
})
.segment('s4', {
templateUrl: 'Views/UserDetailsPage.html',
controller: 'userDetailsController'
})
$routeProvider.otherwise({ redirectTo: '/Home' });
}]);
And I want to call the segment s4 through method call using $location.path()
authService.login($scope.loginData).then(function (response) {
$location.path('/UserDetails');
}
Try it by adding # before the url.
authService.login($scope.loginData).then(function (response) {
$location.path('/#/UserDetails');
}
Also, you can use segment name with getSegmentUrl to get the hash instead of the direct url
authService.login($scope.loginData).then(function (response) {
$location.path($routeSegment.getSegmentUrl('s4'));
}
I was able to get the firebaseSimpleLogin working and storing the current user in the rootScope. When I goto another page and come back to the feed page everything loads, but when I refresh $rootScope.currentUser is null. Has anyone else had this issue?
I have this piece of code in my app.run function:
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
And this is my FeedCtrl that is trying to load in the user's posts
app.controller('FeedCtrl',['$scope', '$rootScope','User','Auth','Post',function($scope, $rootScope,User,Auth,Post){
populateFeed();
console.log($rootScope.currentUser);
$scope.logout = function(){
Auth.logout();
};
$scope.savePost = function(){
Post.create($scope.post).then(function(post){
$scope.post.text = "";
});
};
function populateFeed(){
$scope.posts = {};
angular.forEach($rootScope.currentUser.posts,function(id){
$scope.posts[id] = Post.find(id);
});
}
}]);
My Main app Module
var app = angular.module('myapp',['ui.router','firebase']);
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('/',{
url: '/',
controller: 'MainCtrl',
templateUrl: 'views/index.html'
})
.state('feed',{
url: '/feed',
controller: 'FeedCtrl',
templateUrl: 'views/feed.html',
authenticate: true
})
.state('login',{
url: '/login',
controller: 'LoginCtrl',
templateUrl: 'views/login.html'
})
.state('signup',{
url: '/signup',
controller: 'LoginCtrl',
templateUrl: 'views/signup.html'
})
.state('settings',{
url: '/settings',
controller: 'SettingsCtrl',
templateUrl:"views/settings.html"
})
.state('profile',{
url: '/:slug',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
})
.state('profile-about',{
url: '/:slug/about',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
});
$urlRouterProvider.otherwise('/');
})
.constant('FIREBASE_URL','https://{FIREBASE}.firebaseio.com/')
.run(function($rootScope, $state,FIREBASE_URL, $firebaseSimpleLogin, User, Auth){
$rootScope.$on('$stateChangeStart',function(event, next){
if(next.authenticate && !User.getCurrentUser()){
$state.go('login');
}
});
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
$rootScope.$on('$firebaseSimpleLogin:logout',function(){
delete $rootScope.currentUser;
$state.go('login');
});
$rootScope.logout = function(){
Auth.logout();
};
});
If you by 'refresh' mean that you hit F5 in the browser that will wipe your $rootscope from memory and you will get null back as you experience (basically your entire app will be 'restarted').
In order to persist values you either need to store them in a cookie or use localStorage/sessionStorage. For example, instead of using $rootscope.currentUser use $window.sessionStorage.currentUser.
To store it in localStorage:
$window.localStorage.setItem("currentUser", currentUser);
or store in json format:
$window.localStorage.setItem("currentUser", angular.toJson(currentUser));
To get it form there:
var currentUser = $window.localStorage.getItem("currentUser");
or if you saved it using the second way:
var currentUser = JSON.parse($window.localStorage.getItem("currentUser"));