Setting a cookie in AJAX request with AngularJS - angularjs

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

Related

Redirect to another page with $location.url wont work

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');

Using AngularJS or how to call rest services from CustomApp

I would like to know if it is possible to add angularjs to the custom app in Rally, or as alternative how to call REST services from a Rally Custom app. Can someone help me with this? Thanks in advance.
Best Regards
Here is an example of making a WS API call from an Angular app from inside Rally's custom page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myapp">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<div ng-controller="MyController" >
<button ng-click="myData.doClick(item, $event)">Send AJAX Request to Rally</button>
<br/>
Data from server: {{myData.fromServer}}
</div>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myData = {};
$scope.myData.doClick = function(item, event) {
var responsePromise = $http.get("https://rally1.rallydev.com/slm/webservice/v2.0/defect");
responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.QueryResult.Results[0];
console.log(data);
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
}
} );
</script>
</div>
</body>
</html>
Using external CDN within app is expected to produce Mixed Content error if accessing over http. It works if https is used. Here is the first query result (a defect from my current project) is returned.

$ng-resource doesn't work?

I'm new to AngularJS, I would like to update my data.json but that I don't know where my file users.json should be and I have this error:
Error: $injector:modulerr
http://errors.angularjs.org/1.3.14/$injector/modulerr?p0
Heres my code :
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', ['ngResource']);
app.factory('User', ['$resource',
function($resource){
return $resource('/users/:userId', {userId:'#id'},
{
'update': {method: 'PUT'}
}
);
}
]);
app.controller('UsersCtrl', function ($scope, User) {
$scope.users = User.query();
$scope.validate=function(user) {
user.$update();
}
$scope.delete=function(user) {
user.$delete();
}
$scope.create = function (newUserName) {
var user = new User();
user.name = newUserName;
user.$save();
$scope.users.push(user);
}
});
</script>
<body ng-app="myApp" ng-controller="UsersCtrl">
<ul>
<li ng-repeat="user in users">
<input type="text" ng-model="user.name" />
<button ng-click="validate(user)">Valider</button>
<button ng-click="delete(user)">Supprimer</button>
</li>
</ul>
Nouveau utilisateur :
<input type="text" ng-model="newUserName" />
<button ng-click="create(newUserName)">Créer</button>
</body>
</html>
Anyone have an idea please?
You forgot to add the ngResource file.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
From ngResource page:
You can download this file from the following places:
Google CDN
e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-resource.js
Bower
e.g. bower install angular-resource#X.Y.Z
code.angularjs.org
e.g. "//code.angularjs.org/X.Y.Z/angular-resource.js" where X.Y.Z
is the AngularJS version you are running.
Working Fiddle: http://jsfiddle.net/softvar/rq9eupee/1/
Add angular-resource script below the angular.js file depending upon the version you need within head tag.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
If you want to read some data from the file users.json, have it on server(Backend) and populate it as per your requirements. If you simply want to show the list of users, fetch it from server, server will read the file and returns it contents. If for some purpose, you need to read the file and display it contents on front-end, have it inside your js/ folder. But assuming, you read it to send the response, it should be on backend.

AngularFire createUser example not working outside of Firebase website

In an attempt to learn AngularFire, I've been messing around with AngularFire user authentication methods. On the Firebase website, an example is given that, when I plug in my Firebase address in the proper place, works. When I copy and paste the code into Notepad++ and attempt to run it that way, the HTML works, but none of the Javascript does. I added an alert box to the Javascript, and on opening the page, the alert box popped up, but none of the rest of the JS worked. I feel like I'm missing something very obvious. What am I doing wrong?
Thanks for any help!
My code is as follows:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"> </script>
</head>
<body>
<script>
var app = angular.module("sampleApp", ["firebase"]);
// let's create a re-usable factory that generates the $firebaseAuth instance
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com/?page=Auth");
return $firebaseAuth(ref);
}
]);
// and use it in our controller
app.controller("SampleCtrl", ["$scope", "Auth",
function($scope, Auth) {
$scope.createUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function(userData) {
$scope.message = "User created with uid: " + userData.uid;
}).catch(function(error) {
$scope.error = error;
});
};
$scope.removeUser = function() {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function() {
$scope.message = "User removed";
}).catch(function(error) {
$scope.error = error;
});
};
}
]);
</script>
<div ng-app="sampleApp" ng-controller="SampleCtrl">
Email: <input type="text" ng-model="email">
Password: <input type="text" ng-model="password">
<br><br>
<button ng-click="createUser()">Create User</button>
<br><br>
<button ng-click="removeUser()">Remove User</button>
<p ng-if="message">Message: <strong>{{ message }}</strong></p>
<p ng-if="error">Error: <strong>{{ error }}</strong></p>
</div>
</body>
</html>
I think what has happened is that you have used the ng-app directive twice in your html. If you look at the Angular documentation for ng-app, the first ng-app tag is auto bootstrapped as an application, any additional ng-app have to be manually loaded. Also, you cannot nest applications in a page. When I tried to run your application the SampleCtrl controller is undefined.
I've removed the first ng-app directive and the rest of your code seems to work fine in this plunker I've created.
<!DOCTYPE html>
<!--
ng-app directive is already delclared in the body, removing this one
<html ng-app>
-->
<html>
<head>
...
</head>
<body>
<div ng-app="sampleApp" ng-controller="SampleCtrl">
...
</body>
</html>

AngularJS simple Loginform

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.

Categories

Resources