JMS Serializer unable to return a response - angularjs

I recently included JMS Serializer bundle to handle and convert arrays into JSON
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
public function searchcarAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
// $car = array();
//$cars = $em->getRepository('VehicleBundle:Car')->findAll();
// foreach ($cars as $cart) {
// $car[] = array('id'=>$cart->getId(),'name' => $cart->getName());
// }
$cars = array('name' => 'john','middlename'=> 'gon');
$serializer = $this->container->get('jms_serializer');
$jsonGroup= $serializer->serialize($cars,'json');
return $jsonGroup;
}
public function carAction()
{
return $this->render('VehicleBundle:Car:car_search.html.twig');
}
car.yml
search_car:
path: /car-search
defaults: { _controller: "VehicleBundle:Car:searchcar" }
car_action:
path: /search
defaults: { _controller: "VehicleBundle:Car:car" }
The JMS Serialiser is registeres in AppKernel.php
This will return 500 error
The controller must return a response ({"name":"john","middlename":"gon"} given).
if (null === $response) {
$msg .=' Did you forget to add a return statement somewhere in your controller?';
}
throw new \LogicException($msg);
}
}
return $this->filterResponse($response, $request, $type);
Whats wrong with my controller?
template
car_search.html.twig
{% extends '::base.html.twig' %}
{% block body %}
<div ng-app="myApp" ng-controller="customersCtrl">
Search your Groups Here: <input type="text" ng-model="searchMe.name"/>
<input type="checkbox" ng-model="exactMatch"/>Exact Match<br/>
<div class="[ form-group ]">
<input type="checkbox" ng-model="click" name="fancy-checkbox-default" id="fancy-checkbox-default" autocomplete="off" />
<div class="[ btn-group ]">
<label for="fancy-checkbox-default" class="[ btn btn-default ]">
<span class="[ glyphicon glyphicon-ok ]"></span>
<span> </span>
</label>
<label for="fancy-checkbox-default" class="[ btn btn-default active ]">
Hide
</label>
</div>
</div>
<table id="table" class="table" ng-hide="click">
<thead>
<tr>
<th>Name</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in names | filter:searchMe:exactMatch | limitTo: 2">
<td>//x.name//</td>
<td>//x.model//</td>
</tr>
</tbody>
</table>
</div>
{% endblock %}
{% block javascripts %}
{#{ parent() }#}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.angularjs.org/1.4.8/angular.js"></script>
<script>
var app = angular.module('myApp', []);
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
app.controller('customersCtrl',['$scope','$http',function($scope, $http) {
//$http.get("http://localhost:8093/voters/voters_angular")
$http.get("{{ path('search_car') }}")
.success(function (response) {
$scope.names= JSON.parse(response);
});
}]);
//console.log(names);
</script>
{% endblock %}
Is JMS serializer not working here?

You are returning a string instead of Response object from your controller.
Instead of:
return $jsonGroup;
You should return response, like so for example:
return new \Symfony\Component\HttpFoundation\Response($jsonGroup, 200, ['Content-Type' => 'application/json']);

Related

How to create dynamic ng-model bindings , using dynamic templates

so following is my Dynamically created template, it has an issue, when i add my template, it brings values from the previous DOM. Where was i want new to be empty.
Following is my HTML file, and my-custom-row-template is where i am repeating my template, now i assume that $index will create a new index, and values/DOM wouldn't repeat.
<section class="main_container">
<div class="container">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()"/></th>
<th scope="col">Setup Responses</th>
<th>Add Condition</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="personalDetail in personalDetails">
<td scope="col">
<input type="checkbox" ng-model="personalDetail.selected"/>
</td>
<td scope="col" class="col-xs-10">
<div ng-repeat="condition_set in conditions track by $index" my-custom-row-template></div>
</td>
</td>
<td scope="col">
<input type="button" value="Add Condition" ng-click="addCondition()"
class="btn btn-primary addnew"/>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!personalDetails.length" type="button"
class="btn btn-danger pull-right"
ng-click="remove()" value="Remove">
<input type="button" class="btn btn-primary addnew pull-right" value="Add New" ng-click="addNew()">
<input type="submit" class="btn btn-primary pull-right" value="Save">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</span>
And this is my template code
<div class="col-xs-8 pull-left">
<div class="row form-group">
<!--<select ng-model="response.condition" style="color: black;">-->
<!--<option>Response Message</option>-->
<!--<option>IF</option>-->
<!--<option>Else</option>-->
<!--</select>-->
<select ng-model="selectedCondition[$index]">
<option ng-repeat="x in conditions.condition_set" value="{{x.name}}">{{x.value}}</option>
</select>
<input ng-show="selectedCondition=='0'" type="text" class="form-control"
ng-model="personalDetail[$index].message"/>
<input ng-show="selectedCondition=='1'" type="text" class="form-control"
ng-model="conditions[$index].response"/>
<input ng-show="selectedCondition=='2'" type="text" class="form-control"
ng-model="conditions[$index].elseMessage"/>
<select ng-show="selectedCondition=='1'" ng-model="goToStepOrNew">
<option ng-repeat="x in conditions[$index].create_new_conditions" value="{{x.name}}">{{x.value}}</option>
</select>
<input type="button" value="Remove Condition" ng-click="remove_condition($index)" class="btn btn-danger"/>
</div>
</div>
And this is how i am handling it within my controller
$http({
method: "POST",
url: "team_lead_showed_contacts/ajax",
data: $.param(obj),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformResponse: [function (data) {
var str = '';
str = data.toString();
str = str.replace(/\\/g, 0);
return str;
}]
}).then(function (response) {
//debugger;
$scope.campaigns = JSON.parse(response.data);
$scope.personalDetails = [
{
'add_tempalte': '<div my-custom-row-template> </div>',
}
];
$scope.addNew = function (personalDetail) {
$scope.personalDetails.push({
'add_template': '<div my-custom-row-template> </div>',
});
};
function triggerNewRow($scope) {
if ($scope.goToStepOrNew == 0) {
}
}
$scope.remove = function () {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.personalDetails, function (selected) {
if (!selected.selected) {
newDataList.push(selected);
}
});
$scope.personalDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.personalDetails, function (personalDetail) {
personalDetail.selected = $scope.selectedAll;
});
};
$scope.conditions = [];
$scope.conditions.push('myCustomRowTemplate');
$index = 0;
$scope.addCondition = function () {
$scope.conditions.push('myCustomRowTemplate');
};
$scope.conditions.condition_set = [
{name: 0, value: 'Response Message'},
{name: 1, value: 'IF'},
{name: 2, value: "ELSE"}
];
$scope.conditions.create_new_conditions = [
{name: 0, value: 'Create Step'},
];
$scope.remove_condition = function (element) {
$scope.conditions.splice(element, 1);
// console.log(element);
};
});
For Reference i am attaching an image to give an idea, to what happens when i copy Add New. Copy of already present Elements is pushed into the DOM.
EDIT
Tried some thing like this following Kinda same issue like this post
but no effect.
$scope.personalDetails = [
{
'add_template': '<div my-custom-row-template> </div>',
}
];
var newStep = angular.copy($scope.personalDetails);
$scope.addNew = function (personalDetail) {
$scope.personalDetails.push(
newStep
);
};

Angular JS page loading error

I am new to angular and I tried to create a application to add, update and delete information about the lab test. But when the page is loaded one error occurrs. If anybody knows the reason for this please help me. Thank you.
Error
enter image description here
ManageLabTest.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Lab Test Management</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="../app.module.js"></script>
<script src="../Controller/LabController.js"></script>
<script src="../Controller/main.route.js"></script>
</head>
<body ng-controller="ManageLabTest">
<div id="page">
<div class="header"><img src="../img/logoPCU%20(2).jpg" height="174" width="721"/>
<h1 class="text-info">Lab Test Details Management</h1>
</div>
</div>
<div class="container">
<div class="navigation">
<div class="page-header">
</div>
<div class="well well-lg">
<div class="container-fluid">
<h3><strong>Lab Test Details</strong></h3>
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<div class="form-group">
<label>Patient ID </label>
<input type='text' class="form-control" ng-model="Test.patientID"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Test Code</label>
<input type='text' class="form-control"ng-model="Test.testCode" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Test Name</label>
<input type='text' class="form-control" ng-model="Test.testName"/>
</div>
</div>
<div class="container">
<div class='col-md-3 '>
<div class="form-group">
<label>Type</label>
<select ng-model="Test.type" class="form-control">
<option>Select Type</option>
<option>Critical</option>
<option>Non-Critical</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Date</label>
<div ng-model="Prescription.date">{{date | date:'yyyy-MM-dd'}}</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right" ng-submit="addNew()">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New"/>
<button class="btn btn-warning" id="clear" ng-click="clear()" onclick="enableAddButton()">
Clear
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="page-header">
<h3><strong>Add Lab Test</strong></h3>
</div>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="data-table2">
<tr>
<th> Patient ID </th>
<th> Type </th>
<th> Test Code </th>
<th> Test Name </th>
<th> Date</th>
<th> Edit </th>
<th> Delete</th>
</tr>
<tr ng-repeat="Test in Tests">
<td> {{Test.patientID}} </td>
<td> {{Test.type}} </td>
<td> {{Test.testCode}} </td>
<td> {{Test.testName}} </td>
<td> {{Test.date}} </td>
<td>
<button class="btn btn-warning btn-sm" ng-click="editLab(Test._id)"
onclick="enableUpdateButtons()">Edit <span
class="glyphicon glyphicon-pencil"></span></button>
</td>
<td>
<button class="btn btn-danger btn-sm" ng-click="deleteLab(Test._id)">Delete <span
class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right">
<button class="btn btn-success btn-sm" ng-click="" onclick="">Save/Send</button>
</div>
</div>
</div>
<div class="page-header">
<h3><strong>Lab Test Details</strong></h3>
</div>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="data-table">
<tr>
<th> Patient ID </th>
<th> Type </th>
<th> Test Code </th>
<th> Test Name </th>
<th> Date</th>
<th> Edit </th>
<th> Delete</th>
</tr>
<tr ng-repeat="Test in Tests">
<td> {{Test.patientID}} </td>
<td> {{Test.type}} </td>
<td> {{Test.testCode}} </td>
<td> {{Test.testName}} </td>
<td> {{Test.date}} </td>
<td>
<button class="btn btn-warning btn-sm" ng-click="editLab(Test._id)"
onclick="enableUpdateButtons()">Edit <span
class="glyphicon glyphicon-pencil"></span></button>
</td>
<td>
<button class="btn btn-danger btn-sm" ng-click="deleteLab(Test._id)">Delete <span
class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right">
<button class="btn btn-success btn-sm" ng-click="" onclick="">Save changers</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
LabController.js
'use strict';
angular.module('app').controller('ManageLabTest', ['$scope', function ($scope) {
getLab();
function getLab() {
$http.get('/').then(response => {
$scope.labs = labs;
$scope.lab = null;
});
};
$scope.clear=function(){
$scope.lab=null;
};
$scope.addLab = () => {
$http.post('/',$scope.lab).then(function(response){
getLab();
});
};
$scope.update = () =>{
$http.put('/'+$scope.lab._id,$scope.lab).then(function(response){
getLab();
clear();
});
};
$scope.edit = () =>{
$http.get('/'+id).then(function(response){
$scope.lab = response.data;
});
};
$scope.remove = () =>{
$http.delete('/'+id).then(function(response){
getLab();
});
};
$scope.Test = [];
$scope.addNew = function (Test) {
$scope.Test.push({
'patientID':"",
'testCode':"",
'testName':"",
'date':""
});
};
$scope.date = new Date();
}]);
Lab.model.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LabTestSchema = new Schema({
patientID: {
type: String,
required: true
},
testCode: {
type: String,
required: true
},
testName: {
type: String,
required: true
},
date: {
type: Date,
required: true
},
type:{
type: String,
required: true
}
});
var LabTest = mongoose.model('LabTest', LabTestSchema);
module.exports = LabTest;
app.module.js
angular.module('app',['ngRoute']);
server.js
const bodyParser = require('body-parser'),
express = require('express'),
mongoose = require('mongoose');
mongoose.Promise = global.Promise;
require('./Interface/DataModel/prescription.model.js');
require('./Interface/DataModel/Lab.model.js');
const PresRouter = require('./Interface/Routers/Prescription.route.js');
const LabRouter = require('./Interface/Routers/Lab.route.js')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
mongoose.connect('mongodb://localhost:27017/PCU', err => {
if (err) {
console.log(err);
process.exit(1);
}
}
);
app.use(express.static(__dirname+'/Interface'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/Interface/Pres&Labs/ManageLabTest.html');
});
app.use('/',PresRouter);
app.use('/',LabRouter);
app.listen(3000, err => {
if (err) {
console.error(err);
return;
}
console.log('app listening on port 3000');
});
Lab.route.js
'use strict';
const express = require('express');
const mongoose = require('mongoose');
mongoose.set('debug', false);
const router = express.Router();
const LabModel = require('../DataModel/Lab.model.js');
router.get('/',function (req,res) {
LabModel.find().then(labs => {
res.json(labs);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.post('/',function (req,res) {
const lab = new LabModel(req.body);
labs.save().then(labs => {
res.json(labs);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.get('/:id',function (req,res) {
LabModel.findById(req.params.id).then(data=>{
res.json(data || {});
}).catch(err=>{
console.error(err);
res.sendStatus(500);
});
});
router.put('/:id',function (req,res) {
const data = req.body;
delete data._id;
const Id = req.params.id;
LabModel.findByIdAndUpdate(Id,{$set:data}).then(db=>{
res.json(data);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.delete('/:id',function (req,res) {
LabModel.findByIdAndRemove(req.params.id).then(data=>{
res.sendStatus(200,'success');
});
});
module.exports = router;
main.route.js
angular.module('app').config(['$routeProvider'],function ($routeProvider) {
$routeProvider
.when('/ManagePrescription',{
templateUrl : 'ManagePrescription.html',
controller : 'ManagePrescription'
})
.when('/ManageLabTest',{
templateUrl : 'ManageLabTest.html',
controller : 'ManageLabTest'
})
.when('SearchPrescription',{
templateUrl : 'SearchPrescription.html',
controller : 'ManagePrescription'
})
.when('SearchLabTest',{
templateUrl : 'SearchLabTest.html',
controller : 'ManageLabTest'
});
});
There is syntax error in main.route.js
you are defining your function out of Array..
angular.module('app').config(['$routeProvider'],function ($routeProvider) {
//YOUR LOGIC
});
The code should look like as below
angular.module('app').config(['$routeProvider',function ($routeProvider) {
//YOUR LOGIC
}]);

Pushing Object to array does not reflect at ng-repeat

I am updating an array by pushing the Json object returned by MVC controller to an array in Angular JS controller.
Following is the code sports-controller.js
portsApp.controller("SportsController", ["$scope","$http",function ($scope,$http) {
$scope.data = { id: "rehmat" };
$scope.sports = [];
$scope.selectedSport ={};
$scope.sportsObj = {};
$scope.SportsModel = {};
$scope.sport = {};
$scope.remoteUrlRequestFn = function (str) {
return { term: str };
};
function genericSuccess(res) {
return res.data; // yes, really.
}
$scope.selectedSport = function (selected) {
$scope.sport =
{
title: selected.originalObject.name,
parent_id: selected.originalObject.parent,
sports_id: selected.originalObject.sports_id,
user_id: selected.originalObject.uid
}
$http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
$scope.sports.push(genericSuccess(data).sport);
console.log($scope.sports);
});
}
$scope.UpdateSport = function (id) {
if(id > 0)
{
$http.post("/usersports/update_sports", { user_sport_id: id }).then(function (data,status,headers,config){
if(data.Success)
{
alert(data.Message)
}else
{
alert(data.Message)
}
})
}
}
}
])
VIEW :
<div class="container sports-c" ng-app="SportsApp" >
<!--ADD SPORTS TEXT-->
<div class="col-lg-12" ng-controller="SportsController">
{{sports}}
<div class="add-sports-text ">
<h1 style="text-align:center;" class="animated jello">ADD SPORTS</h1>
<hr style="width:30%">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
</p>
</div>
<div class="form-group" style="text-align:center;">
<label for="search" style="text-align:center;"> SEARCH</label>
<angucomplete-alt id="sports_input_box"
placeholder="Search Sports"
pause="400"
selected-object="selectedSport"
remote-url="/ajax/getSports"
remote-url-request-formatter="remoteUrlRequestFn"
remote-url-data-field="items"
title-field="name"
minlength="2"
input-class="form-control input-custom" />
#*<input type="Search" placeholder="SEARCH" class="form-control input-custom" id="sports_input_box">*#
</div>
</div>
<div class="col-lg-12">
<div class="table-responsive">
{{sports.length}}
<table class="table table-bordered " id="sports-table">
<tr>
<td>ID</td>
<td>SPORTS NAME</td>
<td>SELECT SKILL LEVEL</td>
<td>ACTION</td>
</tr>
<tbody>
<tr ng-repeat="item in sports">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td style="position: relative;top: 10px;">
<select class="example" name="" ng-change="updatePlayerSkill(item.id)" ng-bind="SportsModel.skill_level">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</td>
<td class="icons-tab">
<i class="fa fa-check-square-o" aria-hidden="true" ng-click="UpdateSport(item.id)"></i>
<i class="fa fa-trash-o" aria-hidden="true" ng-click="RemoveSport(item.id)"></i>
</td>
</tr>
<tr ng-show="sports.length === 0"><td colspan="5">No Sports Added</td></tr>
</tbody>
</table>
</div>
</div>
</div>
What is a possible solution for this since I am updating the array by pushing the elements and its not reflecting?
I am using Angular Js 1.6, any help would be really appreciated.
please check the image
Try to surround the code that is pushing the element in the array with a $timeout (Don't forget to inject the $timeout in your controller). This will trigger the diggest cycle and update the bindings, as can be seen here.
`
$http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
$timeout(function(){
$scope.sports.push(genericSuccess(data).sport);
console.log($scope.sports);
});
});
`
The error is caused because from what I see in angucomplete-alt library, the selected parameter can be null. You need to handle that:
$scope.countrySelected = function(selected) {
if (selected) {
window.alert('You have selected ' + selected.title);
} else {
console.log('cleared');
}
};
Regarding your primary question. Using asynchronus requests, it could happen that you go out of Angular $digest cycle. Try to wrap array.push with $scope.applyAsync() to refresh the view.

AngularJS and ModelForm: Submit button not working

The page is supposed to display the contents of the database in a table, with a "New" button to add a new entry to the db. When the user clicks the "New" button, a form appears below. It is a ModelForm for the user to input a new entry to the Model, and then submit via a "Submit" button below. This was working as expected, until I added in an AngularJS controller to handle the button click of "New". The problem is my "Submit" button does not work. I want it to submit the data to the ModelForm, but it appears to do nothing.
Here is my template:
{% extends "base.html" %}
{% block content %}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div class="container-fluid">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<h2>Ratings</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Beer Name</th>
<th>Beer Rating</th>
<th>Notes</th>
<th>Brewer</th>
</tr>
</thead>
<tbody>
{% for rating in ratings %}
<tr>
<td>{{ rating.beer_name }}</td>
<td>{{ rating.score }}</td>
<td>{{ rating.notes }}</td>
<td>{{ rating.brewer }}</td>
<td>Edit</td>
<td><a class="btn btn-primary" href="{% url 'rating-delete' rating.id %}" value="{{ rating.id }}" name="delete" >Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<div ng-app="myApp" ng-controller="myCtrl">
<a ng-model="buttonClick" ng-click="is_clicked()" class="btn btn-primary">New</a>
<div ng-show="buttonClick" ng-cloak>
<div class="container-fluid">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<h2>Enter a new rating</h2>
<form role="form" method="post">
{% csrf_token %}
<p>Beer Name: <input type="text" ng-model="myForm.beer_name"></input></p>
<p>Score: <input type="number" step="0.1" ng-model="myForm.score"></input></p>
<p>Notes: <input type="text" ng-model="myForm.notes"></input></p>
<p>Brewer: <input type="text" ng-model="myForm.brewer"></input></p>
<p><button ng-click="submit_to_form(myForm)" type="submit" class="btn btn-primary">Submit</button></p>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http){
$scope.myForm = {beer_name:'beer_name', score:'score', notes:'notes', brewer:'brewer'};
$scope.buttonClick = false;
$scope.is_clicked = function() {
$scope.buttonClick=true;
console.log($scope.buttonClick)
}
$scope.submit_to_form = function(data) {
$http.post('rating-home', data);
}
})
</script>
{% endblock %}
And urls.py:
from django.conf.urls import url
from django.contrib import admin
from ratings.views import home, RatingCreate, delete, edit
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', RatingCreate.as_view(), name='rating-home'),
url(r'rating/add/$', RatingCreate.as_view(), name='rating-add'),
url(r'rating/delete/(?P<row_id>[0-9]+)/$', delete , name='rating-delete'),
url(r'rating/edit/(?P<row_id>[0-9]+)/$', edit , name='rating-edit'),
]
And views.py for the Submit button:
class RatingCreate(View):
""" Create a new Rating """
form_class = RatingForm
template_name = 'home.html'
def get(self, request):
form = self.form_class()
context = {'ratings': Rating.objects.all(), 'form': form}
#return render(request, 'home.html', context)
return render(request, self.template_name, context)
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
_ = form.save()
return redirect('rating-home')
return render(request, self.template_name, {'form: form'})
You should handle submitting the form with angular
<form ng-submit="myFunc(myData)">
<input type="text" ng-model="myData.name">
<input type="text" ng-model="myData.phone">
<button type="submit">Submit</button>
</form>
OR
<form >
<input type="text" ng-model="myData.name">
<input type="text" ng-model="myData.phone">
<button ng-click="myFunc(myData)">Submit</button>
</form>
and your controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.myData= {name:'' , phone:''};
$scope.myFunc = function(data) {
console.log(data);
// data(myData array) can be send with angular $http.post() method
// e.g. : $http.post('/myUrl/', data)
}
})
Update:
Here is a good tutorial for angular $http service!

List does not refresh in AngularJS

I'm trying to implement a simple crud using Google App Engine (Cloud endpoints) and AngularJs.
I developed my backend and everything working well. My problem is Angular.
After I call my service to Save or Delete, my list doesn't refresh.
My code Controller:
app.controller('admEstadoController',['$scope','admEstadoService', function ($scope, admEstadoService) {
$scope.saveEstado = function() {
admEstadoService.saveEstado($scope);
}
$scope.deleteEstado = function(id) {
admEstadoService.deleteEstado(id,$scope);
}
$scope.listEstado = function() {
admEstadoService.listEstado($scope);
}
}]);
and this is my Service:
app.factory('admEstadoService',[function() {
var admEstadoService = {};
admEstadoService.listEstado = function($scope) {
gapi.client.enadepopapi.listEstado().execute(function(resp) {
$scope.estados = resp.items;
$scope.$apply();
});
}
admEstadoService.saveEstado = function($scope) {
estado = {
"estado" : $scope.estado,
"nome" : $scope.nome
};
gapi.client.enadepopapi.saveEstado(estado).execute();
}
admEstadoService.deleteEstado = function(id,$scope) {
estado = {
"estado" : id
};
gapi.client.enadepopapi.deleteEstado(estado).execute();
}
return admEstadoService;
}]);
And my view is:
<div class="panel panel-default" ng-show="is_backend_ready">
<div class="panel-heading">Manutenção de Estados</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form role="form">
<div class="form-group">
<label for="txtEstado">Estado</label>
<input type="text" class="form-control" id="txtEstado" placeholder="" ng-model="estado">
</div>
<div class="form-group">
<label for="txtNome">Nome</label>
<input type="text" class="form-control" id="txtNome" placeholder="" ng-model="nome">
</div>
<button type="submit" ng-click="saveEstado()" class="btn btn-default">Gravar</button>
</form>
<div class="bs-example-bg-classes" style="margin-top:10px;">
<p class="bg-success"> Registro Gravado com sucesso!</p>
</div>
<div class="clearfix"></div>
<div ng-init="listEstado()">
<table class="table table-hover">
<tbody class="table-hover">
<tr>
<th>Estado</th>
<th>Nome</th>
<th>Operação</th>
</tr>
<tr ng-repeat="estado in estados">
<td>{{estado.estado}}</td>
<td>{{estado.nome}}</td>
<td><button type="button" ng-click="deleteEstado(estado.estado)" class="btn btn-default">Excluir</button>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Even though you update the data in the backend, AngularJS is not aware of this. You need to call listEstado() after save or delete.
However, if you're using ndb as your datastore, be aware that your updated data may not be available instantly because of ndb's eventual consistency behavior.

Resources