Process maker - Login using rest api not working - javascript

Using the below script i am able to retrieve the cases related to a particular user using process makers rest api, but unable to go the home page and use the system as is (Somthing like a single sign on) after doing this, what am i missing here? I am redirecting to the page i want and its taking me to the login screen again. i am using app.js to call the rest api and index.php to display and enter login credentials. I am following this tutorial http://www.processmaker.com/tutorial-rest-api-angularjs, Please help
My app.js is as below:
(function () {
var app;
app = angular.module('caseLister',[]);
app.controller('listController', ['$http', '$scope', function($http, $scope){
this.server_url = 'http://localhost';
this.workspace = 'workflow';
this.credentials = {
grant_type : 'password',
scope : '*',
client_id : 'GFFBDLKMOFFGRLQXELEOIBUVWQXUYANB',
client_secret: '3429870605882e9af901eb4035842469',
username : '',
password : ''
};
var access_token = '';
var list = this;
this.login = function () {
var parameters = {
method: 'POST',
url: list.server_url+list.workspace+'/oauth2/token',
data: this.credentials
};
$http(parameters).success(function(data){
if (data.error) {
alert(data.error_description);
}else {
parameters = {
method: 'GET',
url: list.server_url+'api/1.0/'+list.workspace+'/cases',
headers: {'Authorization': 'Bearer '+data.access_token}
};
$http(parameters).success(function(data){
location.href="http://localhost/sysworkflow/en/neoclassic/cases/main";
list.cases = data;
});
}
});
};
}]);
})();
My index.php is as below:
<!DOCTYPE html>
<html ng-app="caseLister">
<head>
<link rel="shortcut icon" type="image/x-icon" href="http://www.processmaker.com/favicon.ico" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="listController as list">
<div class="panel panel-primary">
<div class="panel-heading">
<h1>ProcessMaker Case Lister</h1>
<h6>Build your own user interface using the new ProcessMaker REST API</h6>
</div>
<div class="panel-body">
<div class="well well-sm col-xs-4 pull-right">
<h4>PM Server details</h4>
<strong>URL:</strong> {{list.server_url}}<br>
<strong>Workspace:</strong> {{list.workspace}}<br>
<strong>Client ID:</strong> {{list.credentials.client_id}}<br>
<strong>Client Secret:</strong> {{list.credentials.client_secret}}
</div>
<form>
<div class="input-group col-xs-6">
<div class="input-group-addon">Username:</div>
<input type="text" class="form-control" ng-model="list.credentials.username">
</div><br>
<div class="input-group col-xs-6">
<div class="input-group-addon">Password:</div>
<input type="password" class="form-control" ng-model="list.credentials.password">
</div><br>
<input class="btn btn-info" type="button" value="Get Case List" ng-click="list.login()"><br>
</form>
<div ng-show="list.cases.length > 0">
<h3>CASE LIST ({{list.cases.length}})</h3>
<table class="table table-hover table-bordered">
<thead><tr class="bg-primary">
<th>#</th>
<th>Case Number</th>
<th>Process</th>
<th>Task</th>
<th>Sent By</th>
<th>Due Date</th>
<th>Status</th></tr></thead>
<tr ng-repeat="case in list.cases">
<td>{{$index + 1}}</td>
<td>{{case.app_number}}</td>
<td>{{case.app_pro_title}}</td>
<td>{{case.app_tas_title}}</td>
<td>{{case.app_del_previous_user}}</td>
<td>{{case.del_task_due_date}}</td>
<td>{{case.app_status}}</td></tr>
</table>
</div>
</div>
</div>
</div>
</body>
</html>

Related

update the data dynamically in AngularJS

I have two end points
http://localhost:3000/entry (POST)
Keys are :- fname, lname and age . We can submit a form by sending a POST request to this URL.
http://localhost:3000/entries (GET)
It will return the existing data from the database in a JSON.
[
{
"_id": "5b48a137c3b2a3454b853a3c",
"fname": "John",
"lname": "Jose",
"age": "28",
"__v": 0
},
{
"_id": "5b506cc7d9105012f59c87e6",
"fname": "Alex",
"lname": "Cruz",
"age": "27",
"__v": 0
}
]
I can successfully submit a form. In my HTML, I also have a table. I want to update the data in the table whenever I submit an entry without reloading the whole page.
Actually, data in this API http://localhost:3000/entries is dynamic, sometimes, I insert into database directly. So, whenever there is a change, it should reflect in the table without reloading the whole page.
I am using AngularJS 1.
index.html :-
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<div ng-app="myApp">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h3>
Dashboard
</h3>
</div>
</div>
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()" >
<div class="col-sm-12">
<div class="form-group">
<label>FirstName</label>
<input type="text" class="form-control" value="" ng-model="form.fname" />
</div>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" value="" ng-model="form.lname" />
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" value="" ng-model="form.age" />
</div>
</div>
<div class="col-sm-12">
<input type="submit" class="btn btn-success" ngClick="Submit">
</div>
</form>
<!-- Table Start -->
<div class="row">
<table style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}</td>
</tr>
</table>
</div>
<!-- Table END -->
</div>
</div>
script.js :-
var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.submitForm = function()
{
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
};
}
});
If I understand your question and problem(s), you'll need to do a number of things to resolve your issues.
Firstly, you'll want to make some extensions to your controller. The main one being to fetch the data from your API:
app.controller('FormCtrl', function ($scope, $http, $interval) {
/*
Add this method to get data from server
*/
$scope.fetchData = function() {
// It is best practice to handle error responses as well (not
// shown here)
$http.get('http://localhost:3000/entries').then(function(response) {
// Set the data items in your scope. Doing this should now
// cause them to be listed in your view
$scope.items = response.data;
});
}
$scope.submitForm = function($event) {
// Adding this prevents the browser from reloading on form submit
$event.preventDefault()
$http({
url: "http://localhost:3000/entry",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.form)
}).then(function (response) {
$scope.status = status;
}), function (error) {
$scope.status = status;
});
}
// Fetch data once controller is set up, on a regular 2 second
// interval
$interval(function() {
$scope.fetchData()
}, 2000)
});
You'll also need to update your HTML/view:
<!-- Add $event as an argument to you ng-submit callback -->
ng-submit="submitForm($event)"
And:
<!-- Doing this causes the data in the items array to be iterated
and displayed in a list-wise fashion in the table -->
<tr ng-repeat="item in items">
<!-- item.fname -->
<td>{{item.fname}}</td>
<!-- item.lname -->
<td>{{item.lname}}</td>
<!-- item.age -->
<td>{{item.age}}
</td>
</tr>
Finally, the most important thing is to wrap the table and form with your FormCtrl controller. You can do this by moving ng-controller="FormCtrl" from your <form> element, to your <div class="container"> element in your view.

$filter ui-grid using search fields

At the moment I have a ui-grid with a full name and registration columns. I also have search fields for both. If user searches for registration, the table is updated 'on the fly'. My issue is that if the user enters both to narrow down the search e.g. registration and name at the same time. The table only reacts on a single filter input.
This is part of my code responsible for watching the field vm.model.employeeName and vm.model.registrationName which are the search fields. vm.resultData is an array of rows to be inserted into vm.gridOptions.data (the ui-grid).
vm.watchFilter = function() {
if (vm.model.employeeName || vm.model.registrationNumber) {
if (vm.model.employeeName) {
vm.updatedResultData = $filter('filter')(vm.resultData, {employeeFullName: vm.model.employeeName});
}
if(vm.model.registrationNumber) {
vm.updatedResultData = $filter('filter')(vm.resultData, {currentVehicleRegistration: vm.model.registrationNumber});
}
vm.gridOptions.data = vm.updatedResultData;
} else {
vm.gridOptions.data = vm.resultData;
}
vm.numberOfRecords = vm.gridOptions.data.length;
};
$scope.$watch('vm.model.employeeName', vm.watchFilter);
$scope.$watch('vm.model.registrationNumber', vm.watchFilter);
How do I combine the 2 to get narrowed down search? I've spent hours on this...
I don't want to end up with if statements for every possible search as I might add an extra search field in the future. Also if a user decides to enter reg first and then name.....
I hope this will help you. Thank you.
var app = angular.module('app', ['ngMessages']);
app.controller('pageCtrl', ['$scope', '$http', function($scope, $http) {
$scope.names = [{"Name":"Mark","Number":"10000"},
{"Name":"Steve","Number":"20000"},
{"Name":"Bill","Number":"30000"},
{"Name":"John","Number":"40000"},
{"Name":"Luis","Number":"50000"}];
$scope.search = function(){
$scope.criteria = angular.copy($scope.criteria1);
}
}]);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-messages.min.js"></script>
<div ng-app="app" class="container" >
<h1>Filter Name & Registeration Number</h1>
<hr />
<form ng-controller="pageCtrl" ng-init='getData()'>
<div class='form-group'>
<div class='row'>
<div class="right-inner-addon col-md-4 ">
<input type="search" ng-model='model.Name' class="form-control" placeholder="Name">
</div>
<div class="right-inner-addon col-md-4 ">
<input type="search" ng-model='model.Number' class="form-control" placeholder="Registeration Number">
</div>
</div>
</div>
<table class="table table-bordered" >
<tr>
<th>Name</th>
<th>Registeration Number</th>
<tr>
<tr ng-repeat="item in filtered = (names | filter : model)">
<td>{{item.Name}}</td>
<td>{{item.Number}}</td>
<tr>
</table>
</form>
</div>

I cannot save data from angular to backend laravel database

I am passing form input from angular to laravel view api. But data cannot be saved in the database. I am getting the following error messages in the console:
error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.0/ngRepeat/dupes?p0=app%20in%20apps&p1=string%3A%3C&p2=%3C
at Error (native)
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:6:416
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:292:254
at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:137:302
at m.$digest (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:138:399)
at m.$apply (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:141:341)
at g (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:94:139)
at t (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:98:260)
at XMLHttpRequest.u.onload (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:99:297)(anonymous function) # angular.js:13236
apps.js:28 0
http://localhost/myapp/public/api/apps Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I also get laravel errors:
<span class="exception_title"><abbr title="Illuminate\Database\QueryException">QueryException</abbr> in <a title="C:\xampp\htdocs\dukamart\vendor\laravel\framework\src\Illuminate\Database\Connection.php line 651" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">Connection.php line 651</a>:</span>
span class="exception_message">SQLSTATE[23000]: Integrity constraint violation: 1048 Column associated with input values.
I have checked my laravel controller seem to be fine. I am posting data from a popup form.
employeeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Employee;
class Employees extends Controller
{
//
public function index($id = null) {
if ($id == null) {
return Employee::orderBy('id', 'asc')->get();
} else {
return $this->show($id);
}
}
public function store(Request $request) {
$employee = new Employee;
$employee->name = $request->input('name');
$employee->email = $request->input('email');
$employee->contact_number = $request->input('contact_number');
$employee->position = $request->input('position');
$employee->save();
return 'Employee record successfully created with id ' . $employee->id;
}
//My angular controller
app.controller('employeesController', function($scope, $http, API_URL) {
//retrieve employees listing from API
$http.get(API_URL + "employees")
.success(function(response) {
$scope.employees = response;
});
//show modal form
$scope.toggle = function(modalstate, id) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Add New Employee";
break;
case 'edit':
$scope.form_title = "Employee Detail";
$scope.id = id;
$http.get(API_URL + 'employees/' + id)
.success(function(response) {
console.log(response);
$scope.employee = response;
});
break;
default:
break;
}
console.log(id);
$('#myModal').modal('show');
}
//save new record / update existing record
$scope.save = function(modalstate, id) {
var url = API_URL + "employees";
//append Employee id to the URL if the form is in edit mode
if (modalstate === 'edit'){
url += "/" + id;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.employee),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
//delete record
$scope.confirmDelete = function(id) {
var isConfirmDelete = confirm('Are you sure you want this record?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'employees/' + id
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Unable to delete');
});
} else {
return false;
}
}
});
When I click to save the data, I am getting an error message I had setup in employeeController.js controller
$http({
method: 'POST',
url: url,
data: $.param($scope.hotel),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarassing. An error has occured. Please check the log for details');
});
}
This my app.js
var app = angular.module(employees, [])
.constant('API_URL', 'http://localhost/myapp/public/api/');
My routes.php
Route::get('/api/v1/employees/{id?}', 'Employees#index');
Route::post('/api/v1/employees', 'Employees#store');
Route::post('/api/v1/employees/{id}', 'Employees#update');
Route::post('/api/v1/employees/update/{id}',['as'=>'update','uses'=> 'Employees#update']);
Route::delete('/api/v1/employees/{id}', 'Employees#destroy');
What could be the cause of this? Please help. I have tried to solve this for 3 days without success.
My View in resources/views/employees/employee.php
<!DOCTYPE html>
<html lang="en-US" ng-app="employeeRecords">
<head>
<title>Laravel 5 AngularJS CRUD Example</title>
<!-- Load Bootstrap CSS -->
<link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">
</head>
<body>
<h2>Employees Database</h2>
<div ng-controller="employeesController">
<!-- Table-to-load-the-data Part -->
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact No</th>
<th>Position</th>
<th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ employee.id }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.contact_number }}</td>
<td>{{ employee.position }}</td>
<td>
<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee.id)">Edit</button>
<button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<!-- End of Table-to-load-the-data Part -->
<!-- Modal (Pop up when detail button clicked) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
</div>
<div class="modal-body">
<form name="frmEmployees" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
ng-model="employee.name" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
ng-model="employee.email" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
ng-model="employee.contact_number" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Position</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
ng-model="employee.position" ng-required="true">
<span class="help-inline"
ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
<script src="<?= asset('app/lib/angular/angular.min.js') ?>"></script>
<script src="<?= asset('js/jquery.min.js') ?>"></script>
<script src="<?= asset('js/bootstrap.min.js') ?>"></script>
<!-- AngularJS Application Scripts -->
<script src="<?= asset('app/app.js') ?>"></script>
<script src="<?= asset('app/controllers/employees.js') ?>"></script>
</body>
</html>
sound like your key is being duplicate in ng-repeat. Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: app in apps, Duplicate key: string:<, Duplicate value: <
this issue happens once
Invalid:
ng-repeat="value in [4, 4]"
valid
ng-repeat="value in [4, 4] track by $index"
In your app.js file.
Change the first line to:
var app = angular.module('employees', ['ngRoute'])

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

Module AngularJS loading-bar doesn't work

I am trying nodeJS, SailsJS & Angular. I want use this loading bar:
http://chieffancypants.github.io/angular-loading-bar/
https://github.com/chieffancypants/angular-loading-bar
I read the loading bar handle http request are automatically.
so i do this :
npm install angular-loading-bar.
I put the jss and css in assets.
Here my LoginModule :
var LoginModule = angular.module('LoginModule', ['angular-loading-bar']);
And my LoginController :
angular.module('LoginModule')
.controller('LoginController', LoginController);
LoginController.$inject = ['$scope', '$http', 'cfpLoadingBar'];
function LoginController($scope, $http, cfpLoadingBar) {
// Get CSRF token and set as header
$http.defaults.headers.post['X-CSRF-Token'] = document.getElementsByName('_csrf')[0].value;
$scope.submitLoginForm = function() {
$scope.start();
$http.post('/login', {
identifiant: $scope.login.identifiant,
password: $scope.login.password
})
.then(function onSuccess() {
window.location = '/home/';
})
.catch(function onError(response) {
console.log(response);
})
}
$scope.start = function() {
cfpLoadingBar.start();
};
$scope.complete = function() {
cfpLoadingBar.complete();
};
}
But when i login on my form :
<div class="container-fluid" ng-app="LoginModule" ng-controller="LoginController" ng-cloak>
<div class=" col-lg-offset-4 col-lg-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Connexion</h3>
</div>
<div class="panel-body">
<h5 class="col-lg-12" style="text-align: center">Admin !</h5>
<form ng-submit="submitLoginForm()" class="col-lg-offset-3 col-lg-6 form-group" name="loginForm">
<input type="text" class="form-control" id="inputLogin" name="inputLogin" placeholder="Identifiant" ng-model="login.identifiant">
<input type="password" class="form-control" id="inputPassword" name="inputPassword" placeholder="Mot de passe" ng-model="login.password">
<br>
<button type="submit" class="btn btn-primary" style="float: right">Connexion</button>
<input type="hidden" name="_csrf" value="<%= _csrf %>">
</form>
</div>
</div>
</div>
</div>
I don't see the loading bar when i submit the form (form working) :( why ? Also when i try to load ngAnimate in LoginModule i have an error
I tried also the function start() on element HTML but nothing..
You Must include angular-animate.min.js to make it work
as also include in git repository example. when I removed this line
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-animate.min.js"></script>
it stopped working please make sure you include animation file. that's why ngAnimate also giving error

Categories

Resources