I've just started to build a prototype in AngularJs/Bootstrap. I'm new to angular but it seem interesting enough to evaluate for some upcoming webprojects.
Step 1 would be to get some simple Loginform to work with hardcoded values and not bother to communicate with the backend service.
However, I read a bunch of tutorials but can't get the routing to work, the mysterious variable $location is always undefined no matter how many times I pass it around. Is perhaps the use of it old-fashioned? I tried some examples from this site but none works, $location is'nt among us anymore it seems?
Last example I tried:
angular.module('myApp.controllers', []).
controller('loginController', ['$scope', function($scope, $route, $routeParams, $location) {
$scope.auth = function() {
//check something useful
$location.url('/view2');
};
}])
If someone has a simple and working example (or an url for a trusted source of information) of a form and a controller that use routing to another partial, I would be delighted.
Regards
I have been struggling with the same issue. I posted this question. The answer shed some light. I was then able to force users to login and only then will they be able to access other links on the navbar. Then I had the issue of nav bar being visible on the login screen. So I created a work-around:
1) I split the pages: using ng-include I was able to load login.html by default. login.html and index.html does not have ng-view.
2) Once the user is authenticated, ng-view must be inlcuded so that all views required on the navigation can work
index.html
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppCtrl">
<div ng-include="template.url"></div>
</body>
</html>
login.html
<h1>Login Page</h1>
<form ng-submit="login(username, password)">
<label>User name</label>
<input type="text" ng-model="username" class="ng-pristine ng-valid">
<label>Password</label>
<input type="password" ng-model="password" class="ng-pristine ng-valid">
<br/>
{{loginError}} {{loggedUser}}
<br/><br/>
<button class="btn btn-success" ng-click="">Submit</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</form>
Then if authentication passes I change templates (ng-include) and make home.html the default page
app.controller('AppCtrl', function($scope, authentication) {
$scope.templates =
[
{ url: 'login.html' },
{ url: 'home.html' }
];
$scope.template = $scope.templates[0];
$scope.login = function (username, password) {
if ( username === 'admin' && password === '1234') {
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.user = username;
} else {
$scope.loginError = "Invalid username/password combination";
};
};
};
Home.html has ng-view which will do the usual and the user has access to other pages.
This is what I have so far, here is a working example, hope it helps.
This would work:
controller('loginController', ['$scope', '$route', '$routeParams', '$location', function($scope, $route, $routeParams, $location) {
$scope.auth = function() {
//check something useful
$location.url('/view2');
};
}])
Each resource you want to inject into your controller should be passed as a string in the array.
Related
I am trying to set a cookie containing a token value retrieved from an Ajax request in AngularJS.
At first, I tested the result of the request by simply displaying the token value in my html page -> {{myToken}}. The result was correct. Now, I am trying to store that value in a cookie. The lines that I added for that purpose are written between **.
In my HTML page, I imported angular.min.js (v1.4.8), then angular-cookies.min.js (v1.6.3):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XXX</title>
<link rel="stylesheet" href="assets/css/style.css" media="screen" type="text/css" />
<script src="assets/scripts/angular.min.js"></script>
</head>
<body >
<div ng-app="myApp" ng-controller="LoginCtrl">
<h1>Log-in</h1><br>
<form>
<input type="text" name="user" placeholder="Username" ng-model="login">
<input type="password" name="password" placeholder="Password" ng-model="password">
<input type="submit" name="login" class="login login-submit" value="login" ng-click="myLogin()">
</form>
<div class="login-help">
<a id="button-login" href="#">Register</a> • Forgot Password
</div>
<p>myToken: {{myToken}}</p>
</div>
**<script src="assets/scripts/angular-cookies.min.js"></script>**
<script src="assets/scripts/myApp.js"></script>
<script src="assets/scripts/controllers/loginCtrl.js"></script>
</body>
</html>
myApp.js is quite simple for now:
var app = angular.module('myApp', [**'ngCookies'**]);
loginCtrl.js contains the Ajax request trigger when calling myLogin().
app.controller('LoginCtrl', function($scope, $http**, $cookieStore**) {
$scope.login = "";
$scope.password = "";
$scope.myLogin = function() {
$http({ <request>})
.then(function(response) {
$scope.myToken = <token value>;
**$cookieStore.put('myToken', $scope.myToken);**
})
};
});
My page is stored on WampServer and when I reach it, I get the following error:
"Error: [$injector:unpr] http://errors.angularjs.org/1.4.8/$injector/unpr?p0=%24cookieStoreProvider%20%3C-%20%24cookieStore%20%3C-%20LoginCtrl
See AnguleJS: API : $cookies and How to access cookies in AngularJS?
Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies
app.controller('LoginCtrl', ['$scope', '$http', '$cookies', function($scope, $http, $cookies) {
$scope.login = "";
$scope.password = "";
$scope.myLogin = function() {
$http({ <request>})
.then(function(response) {
$scope.myToken = <token value>;
$cookies.put('myToken', $scope.myToken);
})
};
}]);
$cookieStore.put('myToken', $scope.myToken); is invalid now you need to use
$cookies.put('myToken', $scope.myToken);
Ok, so I made a few noob mistakes. Here's what's now working for me:
By using minified scripts, I needed to map the scopes "Uncaught Error: [$injector:unpr]" with angular after deployment
I needed to declare the same versions of scripts. I am now using angular.min.js and angular-cookies.min.js version 1.6.3 (Index of /1.6.3/)
As both repliers said, $cookieStores was deprecated a long time ago $cookieStore deprecated
I'm new to AngularJS and i want to redirect my Application from Login.html to Homepage.html. I've read a lot and i found two ways for do that:
the first one consists in using $window.location.hrefand it works perfectly
the second one consist in using $location.url or $location.pathand it doesn't work, it ad just /homepage.html to my actual URL.
How can i solve this?
Here's my code.
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body>
<div ng-app="mainApp" ng-controller="loginController">
<label>Username</label><input type="text" name="username" ng-model="username"><br>
<label>Password</label><input type="password" name="password" ng-model="password"><br>
<button ng-click="login()">Login</button>
<p>{{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('loginController', ['$scope', '$location', function($scope, $location){
$scope.result = null;
$scope.login = function(){
$scope.result = "Logged in";
$location.path('#/localhost/homepage.html').replace();
$scope.apply();
}
}])
</script>
</body>
</html>
Thanks you all anticipatedly!
Not sure if it's important or not, but try changing $scope.apply() to $scope.$apply().
Υου should have:
$location.path('/homepage');
Or:
$location.path('/app/homepage');
I want to save the current state of check box and reload it when open the page next time.
AngularJS:
var app = angular.module('MyApp', []);
app.controller('MyController', function ($scope, $window) {
var init = function () {
$scope.check = $window.localStorage.getItem("app3");
};
init();
$scope.Save = function () {
$window.localStorage.setItem("app3", $scope.check);
}
});
HTML:
<html ng-app="MyApp" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="angular-1.4.9.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input id="check1" type="checkbox" ng-model="check" />
<input type="button" value="Save" ng-click="Save()" />
</div>
</body>
</html>
Dont use jquery with angular.
Attach a ng-model to your input box like so : and you can access the value of the input in your controller using $scope.check
your local storage setting will be like so :
$window.localStorage.setItem('app3',$scope.check);
Thats it! Kindly go through angular tutorials or their documentation to understand how angular works.
I have done this when the service and controller are in a single file (usually, app.js) and it works without any issues.
Now, I have the controllers and services organized in different files and the respective folders. I need to inject 1 particular service in a controller but I am running into an error.
This is a simple angular app that I am working on that has a way to manage your YouTube favorite videos. I am getting the error on the add page. Just click on add button to see the error.
Equivalent Plunker
Here is what I have so far:
index.html
<!doctype html>
<html ng-app="youtube-favorites">
<head>
<title>My YouTube Favorites</title>
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12" style="border: 1px solid red;">
<div ui-view></div>
</div>
</div>
</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="app.js"></script>
<script src="services/add.js"></script>
<script src="controllers/home.js"></script>
<script src="controllers/add.js"></script>
</body>
</html>
app.js
angular.module('youtube-favorites', ['ui.bootstrap', 'ui.router'])
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to /home
$urlRouterProvider.otherwise('/home');
// Now set up the states
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
controller: 'homeController'
})
.state('add', {
url: '/add',
templateUrl: 'views/add.html',
controller: 'addController'
});
}
]);
Controller - add.js
angular.module('youtube-favorites')
.controller('addController', ['$scope', '$log', 'addService',
function($scope, $log, addService) {
$log.info('add');
$scope.addFavorite = function() {
addService.addFavorite($scope.title, $scope.youtubeUrl)
$log.info('title', $scope.title);
$log.info('youtubeUrl', $scope.youtubeUrl);
};
}
]);
Service - add.js
angular.module('youtube-favorites', [])
.service('addService', ['$scope', '$log', '$q', '$window',
function($scope, $log, $q, $window) {
$log.info('add service called');
this.addFavorite = function(title, url) {
$log.info('title', title);
$log.info('url', url);
$window.localStorage.setItem('youtubeFavorites', angular.toJson({
title: title,
url: url
}));
return true;
};
}
]);
View - add.html
<form name="addForm" ng-submit='addFavorite()' novalidate>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" placeholder="Awesome video!" aria-describedby="title" ng-model="title" required />
<!-- <p ng-show="addForm.title.$error.required" class="help-block">Please enter the title.</p> -->
</div>
<div class="form-group">
<label for="youtubeUrl">YouTube <em>embed</em> URL</label>
<input type="text" name="youtubeUrl" class="form-control" placeholder="https://www.youtube.com/embed/someID" aria-describedby="youtubeUrl" ng-model="youtubeUrl" required />
<!-- <p ng-show="addForm.youtubeUrl.$error.required" class="help-block">Please enter the URL.</p> -->
</div>
<div class="form-group">
<button class="btn btn-default grey" type="submit">Submit</button>
</div>
</form>
Here is the error that I am getting:
Pretty sure that I am not injecting the service correctly.
I did try adding the service as a dependency to the app module as per below, but still giving an error.
angular.module('youtube-favorites', ['ui.bootstrap', 'ui.router', 'youtube-favorites.addService'])....
How do I fix this?
In your addService, change this:
angular.module('youtube-favorites', [])
to this:
angular.module('youtube-favorites')
You are effectively creating a new module with the same name when you include the empty [].
Also, you should be passing in $rootScope to your service because $scope is only available to controllers.
You can't inject $scope into a service. You can inject $rootScope, but $scope is a thing that gets injected at the controller level.
Take a look at this stack post for a little more detail.
I have the following two files in Angular, wanting to create a simple Login application. The first one is Login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> AngularJS Login SPA</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" name="username" id="username" ng-model="username"><br/>
Password: <input type="password" name="password" id="password" ng-model="password"><br/>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
</body>
</html>
and the second one is controller.js:
var app = angular.module("mainApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when ('/', {
templateUrl: 'login.html'
})
.when ('#/dashboard',{
resolve:{
"check":function($location, $rootScope){
if (!$rootScope.loggedIn)
{
$location.path('/dashboard');
}
else{
}
}
},
templateUrl: 'dashboard.html'
})
.otherwise ({
redirectTo: '/'
})
});
app.controller('loginCtrl', function($scope, $location, $rootScope){
$scope.submit = function(){
if($scope.username == 'admin' && $scope.password == 'admin')
{
$rootScope.uname = $scope.username;
$rootScope.password = $scope.password;
$rootScope.loggedIn = true;
$location.path('/dashboard');
}
else{
alert('wrong stuff');
}
};
});
The thing is after I succesfully enter the texts 'admin' and 'admin' on username and password (if I click otherwise it correctly shows me an alert), the address changes to .../index.html#/dashboard but it doesn't load me the page dashboard.html, a simple page I created for this app, located in the same folder where index.html is.
Any idea on how it can show me dashboard.html after I succesfully login with the two texts?
Any help could be highly appreciated.
I found out what was the problem.
I had to test the application in Mozilla because Google Chrome doesn't support SPAs (Single Page Applications) that can match a running server.