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
Related
I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:
TypeError: Attempted to assign to readonly property.
This is my controller:
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){
$scope.post = '';
$scope.postCreated = false;
$scope.makeNewPost = function() {
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res){
$scope.postCreated = true;
//extra code not related to the form itself...
};
}]);
My HTML looks like this:
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
I looked this error up and everything I am seeing has nothing to do with what my set up is like.
Please help me out on this. I don't know where to go from here.
Thanks
Try this...
you have initialized $scope.post = ''; as a string. But that should be $scope.post = {}; an object.
var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {
$scope.post = {};
$scope.postCreated = false;
$scope.makeNewPost = function() {
console.log($scope.post.title);
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res) {
$scope.postCreated = true;
//extra code not related to the form itself...
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</div>
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" );
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',
There is another same question asked here, but the solution didn't really solve my problem even after following the instructions from it. However it works with the older version of the firebase only if I put 'OrderByPriority' in the 'ng-repeat' section.
Please help as I'm new to angular and firebase.
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://mock-ng.firebaseio.com/')
.factory('Projects', function($firebaseArray, fbURL) {
return $firebaseArray(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.otherwise({
controller:'ListCtrl',
templateUrl:'list.html'
});
})
.controller('ListCtrl', function($scope, $firebaseArray, 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, $firebaseArray, fbURL, Projects) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebaseArray(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 | 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 class="form-group" name="myForm">
<div class="form-group" ng-class="{error: myForm.name.$invalid}">
<label class="control-label" for="name">Name</label>
<input type="text" class="form-control" name="name" ng-model="project.name" required>
<span class="help-block" ng-show="myForm.name.$error.required">Required</span>
</div>
<div class="form-group" ng-class="{error: myForm.site.$invalid}">
<label class="control-label" for="site">Site URL</label>
<input type="url" class="form-control" name="site" ng-model="project.site" required>
<span class="help-block" ng-show="myForm.site.$error.required">Required</span>
<span class="help-block" ng-show="myForm.site.$error.url">Not a URL</span>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description" ng-model="project.description"></textarea>
</div>
Cancel
<button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="myForm.$invalid">Save</button>
<button type="button" class="btn btn-danger" ng-click="destroy()" ng-show="project.$remove">Delete</button>
</form>
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="libs/jquery-1.11.3.min.js"></script>
<script src="libs/bootstrap/js/bootstrap.js"></script>
<script src="libs/angularjs/angular/angular.js"></script>
<script src="libs/firebase/firebase.js"></script>
<script src="libs/firebase/angularfire.min.js"></script>
<script src="libs/angularjs/angular-route.js"></script>
<script src="libs/datepicker/moment.js"></script>
<script src="libs/datepicker/daterangepicker.js"></script>
<script src="libs/autocomplete/select-tpls.min.js"></script>
<script src="libs/angularjs/dirPagination.js"></script>
<script src="libs/bootstrap/js/ui-bootstrap-tpls-0.12.1.min.js"></script>
<link rel="stylesheet" href="bootstrap.css">
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
Thanks in advance!
This issue is in your EditCtrl. You're using a $firebaseArray() when you want to sync a $firebaseObject().
Plnkr Demo
.value('fbURL', 'https://mock-ng.firebaseio.com/')
// constructor injection for a Firebase database reference
.service('rootRef', ['fbURL', Firebase])
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebaseObject, rootRef) {
// create the project item level reference
var projectRef = rootRef.child($routeParams.projectId)
// synchronize the project as an object, not an array
$scope.project = $firebaseObject(projectRef);
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
});
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.