Navigating through forms AngularJS - javascript

I have two different HTML forms
index.html
home.html
I am trying to create a login in index.html and if it is authenticated i want to navigate to home.html and if its not i am displaying an alert message. But the page does not navigate. Any ideas as to what i am doing wrong?
My code is as follows
index.html
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-view></div>
<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/>
<br/><br/>
<button class="btn btn-success" ng-click="">Submit</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</form>
</div>
<script>
var app = angular.module('myApp', ['ngRoute']);
app.config([ '$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.when('/home', {
templateUrl : 'home.html',
controller : 'HomeController'
}).
$routeProvider.when('/', {
templateUrl : 'index.html',
controller : 'myCtrl'
}).
otherwise({
redirectTo: 'home.html'
});
//$locationProvider.html5Mode(true); //Remove the '#' from URL.
}
]);
app.controller('myCtrl', function($scope,$location) {
// $scope.count = '';
$scope.login = function(username, password) {
if (username == 'admin' && password == '1234')
{
$location.path("/home" );
}
else
{
alert('invalid username and password');
}
}
});
</script>
</body>
home.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="HomeConroller">
<button ng-click="myFunction()">Click Me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('HomeConroller', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
});
</script>
</body>
</html>

Try:
window.location.href = "home.html";
Instead of
$location.path("/home" );

Related

Page not updating in AngularJS

I am creating a web app, where I have one page which is home.html and about.html. In the home.html I have list of users, and when they click on one of the users, it goes to about.html, but does not show the users info. Can anyone check my code, to see what I have done wrong. Thanks in advance.
Here is my code. (home.html)
<form name="myForm">
<label>Search
<input type="text" size="35" ng-model="userSearch">
</label>
</form>
<br/>
<label>Filters</label>
<button type="button" class="btn btn-link">+ Add Filter</button>
<hr>
<legend>Users</legend>
<div class="people" ng-repeat="person in userInfo.lawyers | filter:userSearch" >
<a href="#/lawyer/{{ person.id }}">
<img ng-src="{{person.imgUrl}}"/>
<span class="name">{{person.firstName}} </span>
<span class="name">{{person.lastName}} </span>
<p class="title">{{person.title}} </p>
<span class="date">{{person.date}} </span>
</a>
</div>
About.html
<div class="people-view">
<h2 class="name">{{person.first}}</h2>
<h2 class="name">{{person.last}}</h2>
<span class="title">{{person.title}}</span>
<span class="date">{{person.date}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.last">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Phone:</b>
<input type="num" ng-model="person.phone">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
<b>Education:</b>
<input type="text" ng-model="person.education">
<br>
<b>Education Year:</b>
<input type="text" ng-model="person.year">
<br>
</form>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope) {
//form setting to true
$scope.inactive = true;
$scope.confirmedAction = function() {
isConfirmed.splice($scope.person.id, 1);
location.href = '#/lawyer';
}
});
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
Controller
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
people.getUserInfo().then(function (response) {
$scope.person = people.getUserInfo();
console.log($scope.person.lawyers);
}, function (error) {
console.log(error)
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
isConfirmed = $scope.userInfo;
console.log($scope.userInfo.lawyers);
}, function (error) {
console.log(error)
});
}
});
Services
app.factory('people', ['$http', function($http) {
var userInfo = {
getUserInfo: function () {
return $http.get('https://******************');
}
};
return userInfo;
}]);
As others mentioned, your whole code is in wrong way! but I will try to help as much as I can.
You don't have any method in LawyerController to get the data, so let's begin from that :
change your $routeProvider in app.js like this to have a method :
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html",
method: 'lawyerInit'
})
.otherwise({
redirectTo: '/lawyer'
});
Then change your LawyerController to something like this :
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerInit = function(){
people.getUserInfo().then(function (response) {
$scope.getAll= people.getUserInfo();
for (var i=0; i<=$scope.getAll.length -1; i++){
if($scope.getAll[i].lawyers.id==$routeParams.id){
$scope.person= $scope.getAll[i];
}
}
console.log($scope.person.lawyers);
}, function (error) {
console.log(error)
});
}
}]);
Hope this work, I was not sure how is your json response, if you get error in this line if($scope.getAll[i].lawyers.id==$routeParams.id) you need make sure the id where is exactlly in your json object.

Ui-Router: Every state shows template except one

I have a very frustrating problem...I have a page with four templates and four corresponding states in my angular file. They all work fine except one, 'detail'; I can get to it by clicking the button in the 'home' template, but once there, it will not render the HTML inside the template.
angularApp.js:
var app = angular.module('app', ['ui.router']);
app.factory('auth', ['$http', '$window', function($http, $window){
var auth = {};
auth.saveToken = function(token){
$window.localStorage['app-token'] = token;
};
auth.getToken = function(){
return $window.localStorage['app-token'];
};
auth.isLoggedIn = function(){
var token = auth.getToken();
if(token){
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.exp > Date.now()/1000;
}else {return false;}
};
auth.currentUser = function(){
if(auth.isLoggedIn()){
var token = auth.getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.username;
}
};
auth.register = function(user){
return $http.post('/register', user).success(function(data){
auth.saveToken(data.token);
});
};
auth.logIn = function(user){
return $http.post('/login', user).success(function(data){
auth.saveToken(data.token);
});
};
auth.logOut = function(){
$window.localStorage.removeItem('app-token');
};
return auth;
}]);
app.controller('MainCtrl', [
'$scope',
function($scope){
$scope.greeting = "hello,world";}
]);
app.controller('SecCtrl', ['$scope', function($scope){
$scope.queryObject = {};
}]);
app.controller('AuthCtrl', [
'$scope',
'$state',
'auth',
function($scope, $state, auth){
$scope.user = {};
$scope.register = function(){
auth.register($scope.user).error(function(error){
$scope.error = error;}
).then(function(){
$state.go('home');
});
};
$scope.logIn = function(){
auth.logIn($scope.user).error(function(error){
$scope.error = error;
}).then(function(){
$state.go('home');
});
};
}]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home',{
url: '/home',
templateUrl: '/home.html',
controller: 'SecCtrl'
})
.state('detail',{
url: '/detail',
templateURL: '/detail.html',
controller: 'SecCtrl'
})
.state('login',{
url: '/login',
templateUrl: '/login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth){
if(auth.isLoggedIn()){
$state.go('home');
}
}]
})
.state('register',{
url: '/register',
templateUrl: '/register.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'auth', function($state, auth){
if(auth.isLoggedIn()){
$state.go('home');
}
}]
});
$urlRouterProvider.otherwise('home');
}
]);
index.ejs:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="javascripts/angularApp.js"></script>
</head>
<body ng-app = "app">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html"><a ui-sref="detail">
<button >Go to Details</button></a>
</script>
<script type="text/ng-template" id="/detail.html">
<h1>Details!</h1> <!--This is the part that won't show up -->
</script>
<script type="text/ng-template" id="/login.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-show="error" class="alert alert-danger row">
<span>{{error.message}}</span>
</div>
<form ng-submit="logIn()"
style="margin-top:30px;">
<h3>Log In</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Username"
ng-model="user.username"></input>
</div>
<div class="form-group">
<input type="password"
class="form-control"
placeholder="Password"
ng-model="user.password"></input>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
</script>
<script type="text/ng-template" id="/register.html">
<div class="page-header">
</div>
<div ng-show="error" class="alert alert-danger row">
<span>{{ error.message }}</span>
</div>
<form ng-submit="register()"
style="margin-top:30px;">
<h3>Register</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Username"
ng-model="user.username"></input>
</div>
<div class="form-group">
<input type="password"
class="form-control"
placeholder="Password"
ng-model="user.password"></input>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</script>
</body>
</html>
Thanks in advance for any help you can give!
Try this. Change templateURL to templateUrl:
.state('detail',{
url: '/detail',
templateUrl: '/detail.html',
controller: 'SecCtrl'
})
There is typo in defining templetUrl property name . you wrote it as
templateURL: '/detail.html',
it should be
templateUrl: '/detail.html',

angular ng-submit doesnot work

I am working on a angular-js project. I want to submit a form by ng-submit. But It is not work.
My Html code is
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routes example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body ng-app="sampleApp" class="container">
<div class="btn-group">
List
Add New
</div>
<hr>
<div ng-view></div>
<script>
var module = angular.module("sampleApp", ['ngRoute']);
module.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider.
when('/view', {
templateUrl: 'template/view/list',
controller: 'RouteController'
}).
when('/add', {
templateUrl: 'template/view/new',
controller: 'RouteController'
}).
otherwise({
redirectTo: '/view'
});
$locationProvider.html5Mode(true);
}]);
module.controller("RouteController", function($http,$scope, $routeParams) {
$http.get('welcome/phones').success(function(data) {
$scope.phones = data;
});
$scope.formData = {};
$scope.saveInfo = function() {
formData = $scope.form;
console.log(formData);
$http.post('welcome/save',formData);
}
});
</script>
</body>
</html>
My form template is
<form action="#" ng-submit="saveInfo()" method="post" ng-controller="RouteController">
<div class="form-group">
<label for="">Product</label>
<input type="text" name="name" ng-model="form.name" class="form-control">
</div>
<div class="form-group">
<label for="">Price</label>
<input type="text" name="price" ng-model="form.price" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" value="Submit">
</div>
</form>
My /add,/view roure work fine. But when I submit the form, ng-submit does not work. The form submit directly. I does not get any thing in console. Where is my problem?. Thank you.
Try intializing $scope.form:
$scope.formData = {};
$scope.form = {};
module.controller("RouteController", function($http,$scope, $routeParams) {
$http.get('welcome/phones').success(function(data) {
$scope.phones = data;
});
$scope.formData = {};
$scope.form = {};
$scope.saveInfo = function() {
$scope.formData = $scope.form;
console.log( $scope.formData);
$http.post('welcome/save', $scope.formData);
}
});
Based upon the code you have submitted, you don't intend to use $scope.formData. I think its a typo you made. Just change that like to $scope.form = {}
$scope.form = {}; // instead of $scope.formData

Exception while simulating the effect of invoking '/todos/update'

I am building a TODO application using Angular-Meteor.I am following the tutorial here:
http://angularjs.meteor.com/tutorial/step_06
I have an error while I am trying to access a single todo item:
Here is my app.js
Todos = new Mongo.Collection('todos');
if (Meteor.isClient) {
var todo = angular.module('todo', ['angular-meteor', 'ui.router']);
todo.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('todos', {
url: '/todos',
templateUrl: 'todos-list.ng.html',
controller: 'todoListController'
})
.state('todoDetails', {
url: '/todos/:todoId',
templateUrl: 'todo-details.ng.html',
controller: 'todoDetailsController'
});
$urlRouterProvider.otherwise("/todos");
}]);
todo.controller('todoListController', ['$scope', '$meteor', function($scope, $meteor) {
$scope.todos = $meteor.collection(Todos);
$scope.addTodo = function(todo) {
todo.date = new Date();
$scope.todos.save(todo);
};
$scope.remove = function(todo) {
$scope.todos.remove(todo);
};
$scope.clear = function() {
$scope.todos.remove();
};
}]);
todo.controller('todoDetailsController', ['$scope', '$stateParams','$meteor', function($scope, $stateParams, $meteor) {
$scope.todoId = $stateParams.todoId;
$scope.todo = $meteor.object(Todos, $stateParams.todoId);
}]);
}
My index.html:
<head>
<base href="/">
</head>
<body>
<div ng-app="todo">
<h1>
Home
</h1>
<div ui-view></div>
</div>
</body>
My todo-list.ng.html
<form>
<label for="name">Name</label>
<input type="text" id="name" ng-model="newTodo.name">
<label for="priority">Priority</label>
<input type="text" id="priority" ng-model="newTodo.priority">
<button class="btn btn-primary" ng-click="addTodo(newTodo)">Add Todo</button>
</form>
<ul>
<li ng-repeat="todo in todos track by $index">
{{todo.name}} {{todo.priority}} {{todo.date | date}}
<button class="btn btn-primary" ng-click="remove(todo)">Done</button>
</li>
<h4>Tasks to do: {{todos.length}}</h4>
</ul>
<button class="btn btn-primary" ng-click="clear()">Clear list</button>
And todo-details.ng.html
<h1>Your to do</h1>
<input type="text" ng-model="todo.name">
<input type="text" ng-model="todo.priority">
I have no idea, what am I doing wrong, following the official tutorial step by step, just replace parties with todo, honestly.
Any ideas ?
It turns out it was a bug caused by Meteor itself.
I have created an issue on Github and it was fixed.

AngularJS:Uncaught Error: [$injector:modulerr]

I'm trying AngularJS example given on http://angularjs.org titled Wire up a Backend.
I've copied code and saved files on my machine.
While executing index.html,
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=project&p1=Error%3…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.13%2Fangular.min.js%3A17%3A431)
error is displaying on console.
Any help will be appreciated.
following is the code.
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.5.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://angularjs-projects.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
});
list.html
<input type="text" ng-model="search" class="search-query" placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projects | orderByPriority | filter:search | orderBy:'name'">
<td>{{project.name}}</td>
<td>{{project.description}}</td>
<td>
<i class="icon-pencil"></i>
</td>
</tr>
</tbody>
</table>
detail.html
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">Required {{myForm.name.$pristine}}</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.name.$pristine" class="help-inline">Required</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="project.description"></textarea>
<br>
Cancel
<button ng-click="save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="destroy()"
ng-show="project.$remove" class="btn btn-danger">Delete</button>
</form>
I think it's wrong with your $resource instance Project, which neither been injected in module('project', ['ngRoute', 'firebase']) nor create .factory('Projects').
So you need sth like following i think:
angular.module('project', ['ngRoute', 'firebase'])
.factory('Projects', function($resource) {
return $resource('url:id',
{
id: "#id"
});
})
or create a new module and include in ['ngRoute', 'firebase']

Categories