RESTAngular with factory method is not working - angularjs

Following the tips in
Best practice of RestAngular, I am trying to follow the suggestions (Restangular Service - Factory and exampleService) and it's not working.
The following source code includes two sections one. Without Angular Factory, that works. And with Factory that is not working:
<html ng-app="angularexample">
<head>
<script src="https://code.angularjs.org/1.3.14/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.14/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-Controller='MainCtrl'>
<div ng-repeat="user in users">
Name : {{user.name}}<br>
Age : {{user.age}}<br>
ID : {{user.id}}<br>
Change name:<input type="text" ng-model="user.name"/><button type="submit" ng-click="user.put()">Update</button><br/>
Remove ID:<input type="text" ng-model="user.id"/><button type="submit" ng-click="user.remove()">Delete</button><br/>
</div>
<div>
add new: <br/>
Name : <input type="text" ng-model="newUser.name"/><br/>
Age : <input type="text" ng-model="newUser.age"/><br/>
<button type="submit" ng-click="add()">add</button>
</div>
</div>
<div ng-Controller='ExampleCtrl'>
My Title {{title}} <br/>
<div ng-repeat="user in examples">
Name : {{user.name}}<br>
Age : {{user.age}}<br>
ID : {{user.id}}<br>
Change name:<input type="text" ng-model="user.name"/><button type="submit" ng-click="user.put()">Update</button><br/>
Remove ID:<input type="text" ng-model="user.id"/><button type="submit" ng-click="user.remove()">Delete</button><br/>
</div>
<div>
add new: <br/>
Name : <input type="text" ng-model="newUser.name"/><br/>
Age : <input type="text" ng-model="newUser.age"/><br/>
<button type="submit" ng-click="add()">add</button>
</div>
</div>
</body>
</html>
http://plnkr.co/edit/y22aBpcUwV1btrKB5jVM?p=preview
Here is the error screen:
http://i57.tinypic.com/334rfqu.jpg
The working reference is pictured as my REST service is not hosted . Yet my REST service is just having two fields namely - name and age.
/**
* User.js
*
* #description :: This is the sample Model for Sails JS to create REST API.
* #docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name : {
type : 'string'
},
age : {
type : 'integer'
}
}
};
What could be an issue in my code? I would like to follow the best practices to build a big application.

The code fails because your service methods do not return anything. Update them as follows:
// get examples from server by using Restangular
function getExamples(){
return Restangular.all('user').getList();
}

You are calling the then method without returning the associated promise from your factory methods, you should return the promise, like
// get examples from server by using Restangular
function getExamples(){
return Restangular.all('user').getList();
}
// get example with given id from server by using Restangular
function getExample(exampleId){
return Restangular.one('user', exampleId).get();
}
Now the methods will make the request and return the assoiciated promise on which you can call the then method.

Related

How to get data from an input text in a jsp page in order to insert it into database?

I'm new with spring Mvc and I'm blocked in retrieving data from my input text in my jsp page .
I want to retrieve user data from the form in order to insert it into database using a simple JDBCconnection and making sure that the user doesn't exist into database.
Maybe my code will explain the problem better:
This is the controller responsible of retrieving data and insert it into data base :
#Controller()
public class AddController {
#Inject
#Named(value = "dataSource")
private DataSource dataSource1;
#RequestMapping(value = "/addDB", method = RequestMethod.GET)
public void Add(){
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String insert = "insert into user values(?,?,?,?)";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(insert);
preparedStatement.setString(1,//what to write here );
preparedStatement.setString(2,***);
preparedStatement.setString(3,***);
preparedStatement.setString(4,***);
resultSet = preparedStatement.executeQuery();
}
}
and here is my jsp page :
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:url value="/addDB" var="addUrl" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type='text/javascript'>
$(function() {
$('#add').click(function() {
$.get('${addUrl}');
});
});
</script>
</head>
<body>
<form>
<fieldset style="width: 472px;">
<legend>Add user </legend>
<div>
<p>
<label>num</label> <input name="num" type="text" />
</p>
</div>
<div>
<p>
<label>name</label> <input name="name" type="text" />
</p>
</div>
<div>
<p>
<label>phone</label> <input name="phone" type="text" />
</p>
</div>
<div>
<p>
<label>age</label> <input name="age" type="text" />
</p>
</div>
<div align="center">
<p>
<button class="button" type="button" value="add">add
</button>
</p>
</div>
</fieldset>
</form>
</body>
Is my work correct ? Is there something missing ?
Thanks in advance ..
Since SpringMVC has three layers (Model, View, Controller) you should not include SQL code in your controller. Try creating a DAO class for each persistent class in your project. Your DAO class will has, at least, the insert, update, delete and list methods. Then all you have to do is using the dao clases in your controllers.

Reset form to pre validation state?

We are new to angular and we wanted to use angular validations with our forms. We are using async ajax calls with a kendo grid to get, create, edit and save data without any submit. I am having a hard time figuring out how to reset the validation state of the form when the user chooses to create a new record.
I made this small exaple, trying anything I could find in sof without any luck so far:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-messages.min.js"></script>
<div ng-app="app">
<div ng-controller="ValidationController">
<form name="myForm" novalidate>
<label>
Name
<input name="nombre"
ng-model="field"
required />
</label>
<div ng-messages="myForm.$error">
<div ng-message="required" ng-if="myForm.nombre.$touched" ng-messages-include="myMessages">
</div>
</div>
<button type="button" ng-click="reset(myForm);" value="Reset">reset validation</button>
</form>
<script type="text/ng-template" id="myMessages">
<div ng-message="required">required field</div>
</script>
</div>
</div>
<script>
angular.module('app', ['ngMessages']).controller("ValidationController", function ($scope, $window) {
$scope.reset = function (form) {
form.$setPristine();
form.$setUntouched();
form.$setValidity();
form.nombre.$setPristine();
form.nombre.$setValidity();
form.nombre.$setUntouched();
}
});
</script>
Here is my fiddle:
https://jsfiddle.net/yh9q1a2j/
Update:
I think this better suits your needs. I've updated the fiddle
https://jsfiddle.net/n7qqn1x6/6/
In your reset method call $setPristine along with clearing the formData object.
$scope.formData = {};
$scope.myForm.$setPristine();
To get the error messages to be removed from the page once added I had to use ng-show instead of ng-if
<div ng-show="myForm.nombre.$error.required&&myForm.nombre.$dirty">required</div>

Angular validator, pass data along with error code to be displayed in ngMessages

Is that possible to store some additional data along with the error flag itself, using standard Angular mechanism?
i.e. I'm manually setting ngModel.$setValidity, I'd like to pass some data along with the error flag, to be displayed in ngMessages directive.
For example let's assume the min/max length of the field depends upon some external factors, thus is computed & validated server-side. The server respons with customlength error code along with max and min properties, which I'd like to display to the user.
Currently I'm simply setting ngModel.$setValidity("customlength", false); but I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like <div ng-message="customlength">the length should be between {{ data.min }} and {{ data.max }}
I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like the length should be between {{ data.min }} and {{ data.max }}
Use the root scope to store the value(s) intended to be output within the message string:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.js"></script>
<script>
angular.module('ngMessagesExample',['ngMessages']);
</script>
<body ng-app="ngMessagesExample">
<form name="myForm" id="{{$root.$id}}">
<label>
<p>Enter Min:<input type="text" ng-model="form_min">
<p>Enter Max:<input type="text" ng-model="form_max">
<p>Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="form_min"
ng-maxlength="form_max"
required />
</label>
<p>
<input type="radio" required name="foo" ng-model="foo" value="1">Yes
<input type="radio" required name="foo" ng-model="foo" value="2">No
</p>
<p>
Foo: <input type="text" ng-model="myForm.foo.$modelValue">
</p>
<p>
<input type="submit" value="{{myForm.foo.$error.required ? 'No' : 'Yes'}}">
</p>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.foo.$error" style="color:maroon" role="alert">
<div ng-message="required">Pick one</div>
</div>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">Your value should be between {{form_min}} and {{form_max}} characters long</div>
<div ng-message="minlength" id="{{$id}}">Your value is less than {{form_min}}</div>
<div ng-message="maxlength" id="{{$id}}">Your value is greater than {{form_max}}</div>
</div>
</form>
</body>
References
Easy Form Validation in AngularJS with ngMessages — SitePoint
AngularJS: Developer Guide: Migrating from Previous Versions
Explicitly providing ng-model to DOM elements | TO THE NEW Blog
Using NgModelController with Custom Directives

Binding not working in Angular Tutorial example

<div ng-app="">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
</div>
This is the HTML code they had to demonstrate "Sharing Data Between Controllers" but the bindings inside FirstCtrl and SecondCtrl didn't work for me. Is this way of binding not included in Angular 1.3?
Controllers
function FirstCtrl($scope) {
}
function SecondCtrl($scope) {
}
Original Tutorial Link
Fiddle
As of angular 1.3 you can no longer use global functions as controllers, you must explicitly add them to your module.
Name your module in your markup ng-app="my-app"
Create a module in code var app = angular.module('my-app', []);
Add your controllers to the module app.controller('FirstCtrl', FirstCtrl)
Enjoy data binding

Binding repeatable form subset to model

On a registration form I allow a user to enter zero or more phone numbers. Each phone number consists of a prefix and a number, these are two fields per phone number. The user may decide how many numbers he wants to provide, the add more numbers link would clone this part of the form.
Prefix: [_______]
Number: [_______]
+ add more numbers
The model I bind to is fixed and should be this format:
$scope.model = {
"...main inputs": "username, etc...",
phoneNumbers: [
// for each phone number I expect this object
{ "prefix": "+1", "number": "123123123" }
]
};
I am not sure how I should set up my ng-model for these text inputs to have these objects generated within the array.
Also, I am a great fan of referential binding and limiting things like scope watch and event-based changes to the scope, as often these changes go unnoticed for other directives that may be using this value (unless being watched). Basically that means it is my intention to have dynamic generation of objects within the array as the form is filled in with numbers, or dynamic removal of objects within the array as numbers are removed or both inputs left empty.
The array should only contain valid and filled objects, partially filled objects or empty objects should not be added to the model or array (as usually is done with properties with invalid values -- those properties get removed from the model object). Basically a push to the array with every validated object, and removal (slice) of objects for every invalid object. But then rather automatically, instead of writing a push/slice function.
Hi try out this code:
Html:
<form name="form">
<div data-ng-repeat="phone in phoneNumberArray">
<div class="form-group">
<label for="inputFirstName">Prefix</label>
<input id="prefix" class="form-control" type="text" ng-model="phone.prefix">
</div>
<div class="form-group">
<label for="inputLastName">Phone number</label>
<input id="phoneNumber" class="form-control" type="text" ng-model="phone.phoneNumber">
</div>
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add more number" data-ng-click="addmore()"/>
</div>
Controller:
$scope.phoneNumberArray = [
{
prefix: "",
phoneNumber:"",
}];
$scope.addmore = function () {
$scope.phoneNumberArray.push({
prefix: "",
phoneNumber: "",
});
}
Hi check this demo in Fiddle
Use the following code.....
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app ng-controller="todoCtrl">
<form name="form" ng-submit="addmore()">
<div class="form-group">
<label for="inputFirstName">Prefix</label>
<input class="form-control" type="text" ng-model="phone_prefix"/>
</div>
<div class="form-group">
<label for="inputLastName">Phone number</label>
<input class="form-control" type="text" ng-model="phone_Number"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add more number"/>
</div>
</form>
<div ng-repeat="phone in phoneNumberArray">
{{ phone.prefix + " "+ phone.phoneNumber}}
</div>
<script>
function todoCtrl($scope) {
debugger;
$scope.phoneNumberArray = [
{prefix: '14', phoneNumber:'123'}
];
$scope.addmore = function () {
$scope.phoneNumberArray.push(
{prefix: $scope.phone_prefix, phoneNumber: $scope.phone_Number}
);
}
}
</script>
</body>
</html>

Resources