I'm building a complete crud using laravel + angularjs, but I have problems in the "edit" part.
It's an internal server error, so I don't know what it means and I need help.
Error "GET localhost/crudtcc/public/api/v1/colaboradores/editar/3 500 (Internal Server Error)"
the javascript file:
app.controller('colaboradoresController', function($scope, $http, API_URL) {
$http.get(API_URL + "colaboradores")
.success(function(response) {
$scope.colaboradores = response;
});
$scope.toggle = function(modalstate, id_colaborador) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Novo colaborador";
$scope.colaborador = null;
break;
case 'edit':
$scope.form_title = "Dados do colaborador";
$scope.id_colaborador = id_colaborador;
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
break;
default:
break;
}
$('#myModal').modal('show');
}
$scope.save = function(modalstate, id_colaborador) {
var url = API_URL + "colaboradores/salvar";
if (modalstate === 'edit') {
url += "/editar/" + id_colaborador;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.colaborador),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('Um erro ocorreu. Check a log para mais detalhes.');
});
}
$scope.confirmDelete = function(id_colaborador) {
var isConfirmDelete = confirm('Tem certeza que deseja excluir o registro?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'colaboradores/remover/' + id_colaborador
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Falha na exclusão');
});
} else {
return false;
}
}
});
the routes file:
<?php
namespace App\Http\Controllers;
$colaborador = new Colaborador;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Usuario;
use App\Http\Controllers\Controler;
use App\Colaborador;
class Colaboradores extends Controller
{
public function index()
{
return Colaborador::orderBy('id_colaborador', 'asc')->get();
}
public function salvar(Request $request)
{
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return 'Colaborador salvo com sucesso! ID: ' . $colaborador->id_colaborador;
}
public function update(Request $request,$id_colaborador)
{
$colaborador = Colaborador::find($id_colaborador);
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return "Sucesso atualizando Colaborador #" . $colaborador->id_colaborador;
}
public function remove(Request $request, $id_colaborador)
{
$colaborador = Colaborador::where("id_colaborador", $id_colaborador);
$colaborador->delete();
return "Colaborador #". $request->input('id_colaborador'). " excluido com sucesso!";
}
public function editar($id_colaborador)
{
return Colaborador::where("id_colaborador", $id_colaborador);
}
}
?>
and the routes file...
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get("/colaboradores/gercolaboradores",
function() {
return view("/colaboradores/gerenciarcolaboradores");
});
Route::get("/api/v1/colaboradores/","Colaboradores#index");
Route::get("/api/v1/colaboradores/editar/{id_colaborador}","Colaboradores#editar");
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
Route::post('/api/v1/colaboradores/salvar', 'Colaboradores#salvar');
Route::delete('/api/v1/colaboradores/remover/{id_colaborador}', 'Colaboradores#remove');
?>
You should write your request on Angular side as:
$http.post(API_URL + 'colaboradores/editar/' + id_colaborador, {YOUR_DATA})
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
and pass the parameters you want to send to backend.
Please refer to: https://docs.angularjs.org/api/ng/service/$http.
Explanation:
you're using angular GET
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
and you defined your route in Laravel as POST
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
GET is not passing any data except trough url, and you're trying to get that data as if you've sent it trough POST request.
You can find a short explanation on GET and POST requests on the following links: http://www.w3schools.com/tags/ref_httpmethods.asp and What is the difference between POST and GET?
Related
I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it without refreshing the page. I am using Ajax for this. Let me show you the codes
html
<label for="landacq" class="civil-label">Land Acquisation Cases</label>
<input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden>
<label for="sc" class="civil-label">Supreme Court</label>
<input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden>
<label for="limitation" class="civil-label">Limitation</label>
<input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden>
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (query) {
showCivilQ(query);
// console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
}
function showCivilQ(query) {
q.textContent = query;
console.log(query);
}
So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these values are use to filter the database and return the objects like this
views.py
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
return HttpResponse(query)
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
This is the result I am getting which is correct.
My Question is these objects contain attributes having some values in for eg, title, headnote etc. How can I display these attributes in the html rather than displaying the object names returned as shown in the Image like title of the citation, headnote of the citation etc
A solution could be to return a json object instead of the query resultset; because Ajax works well with json
You need a function that translates a Citation object into a dictionary (change it based on your real attributes). All elements must be translated into strings (see date example)
def citation_as_dict(item):
return {
"attribute1": item.attribute1,
"attribute2": item.attribute2,
"date1": item.date.strftime('%d/%m/%Y')
}
This dictionary must be translated into a json through import json package
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
response_dict = [citation_as_dict(obj) for obj in query]
response_json = json.dumps({"data": response_dict})
return HttpResponse(response_json, content_type='application/json')
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
In your HTML page you should be able to parse the response as a normal JSON object
I figured out another way to do it, which is giving me the required results too.
Here I am filtering the values of the query, and then converting it to a list and passing it as a JsonResponse
views.py
def civil_home(request):
if request.method == "POST" and request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.values().filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
result = list(query)
return JsonResponse({"status": "success", "result": result})
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
And then I am recieving the reponse here and iterrating over it to print the attributes in the html
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (response) {
console.log(response.result);
civilData = response.result;
if ((response.status = "success")) {
$("#queryResult").empty();
for (i = 0; i < civilData.length; i++) {
$("#queryResult").append(
`
${civilData[i].title}
<p>${civilData[i].headnote}</p>
`
);
}
} else {
$("#queryResult").empty();
$("#queryResult").append(
`
<p>No Citations Found</p>
`
);
}
},
error: function (error) {
console.log(error);
},
});
});
}
A csrf_token can be mentioned at the top of the html page and then it can be passed in the header to avoid any conflict.
I ajax post a complex object to a .Net 5.0 controller (not a WebAPI controller). The declaration of the MVC controller and TypeScript are as below. The [HttpPost] Edit action is invoked if I post with <input type='submit' value='Save' />. However, the controller's action is not invoked at all if I post through jQuery .ajax(). The browser console says "POST https://localhost:44381/Question/Edit 400 (Bad Request)". I read many code samples and nothing indicates anything wrong with the code. Does anyone know why?
namespace theProject.Controllers {
public class BaseController: Controller {
protected BaseController(IConfiguration configuration, ILogger logger) {
.......(elided
for brevity)
}
}
}
namespace theProject.Controllers {
//ToDo: [Authorize]
public class QuestionController: BaseController {
public QuestionController(IConfiguration configuration, ILogger < QuestionController > logger): base(configuration, logger) {}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([FromBody] PostbackModel model) {
if (ModelState.IsValid) {
List < UserAnswer > newAnswers = model.NewAnswers;
List < UserAnswer > oldAnswers = model.OldAnswers;
List < UserAnswer > updatedAnswers = model.UpdatedAnswers;
UserAnswer thisAnswer = new();
if (newAnswers != null)
thisAnswer = newAnswers.Find(x => x.StageName != string.Empty);
else if (oldAnswers != null)
thisAnswer = oldAnswers.Find(x => x.StageName != string.Empty);
else if (updatedAnswers != null)
thisAnswer = updatedAnswers.Find(x => x.StageName != string.Empty);
//ToDo: call webapi Question controller to persist the data to database
return RedirectToAction(nameof(Edit), new {
stage = thisAnswer.StageName, personName = thisAnswer.personName, custID = thisAnswer.custID.ToString(), redirectFrom = "Edit"
});
} else {
return RedirectToAction("Index", "Home");
}
}
let postBackModel: AjaxPostbackModel = < AjaxPostbackModel > {};
postBackModel.NewAnswers = newAnswers
postBackModel.OldAnswers = oldAnswers;
postBackModel.UpdatedAnswers = updatedAnswers;
let thisUrl: string = $('form').prop('action');
$.ajax({
type: "POST",
url: thisUrl,
data: JSON.stringify(postBackModel),
contentType: 'application/json; charset=utf-8',
}).done(function(result) {
$('.spinnerContainer').hide();
console.log('postback result', result.message);
console.log('inserted entities', result.insetedEntities);
dialogOptions.title = 'Success';
$('#dialog')
.text('Data is saved. ' + result.message)
.dialog(dialogOptions);
}).fail(function(error) {
console.log('postback error', error);
$('.spinnerContainer').hide();
dialogOptions.title = error.statusText;
dialogOptions.classes = {
'ui-dialog': 'my-dialog',
'ui-dialog-titlebar': 'my-dialog-header'
}
$('#dialog')
.text('Data is not saved')
.dialog(dialogOptions)
});
Since you use [ValidateAntiForgeryToken] in action,you need to add the following code to your ajax to add antoforgery token to header.
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
I got this error and I cant seem to find the bug.
This is the function in my controller.
class ConfigSplitCleansingController extends Controller
{
public function storeNewArea(Request $request)
{
$setArea = $request->setNewArea;
$decode = json_decode($setArea, true);
$activity = Activities::where('activityCode', $request->activityId)->first();
$lastrow = PubCleansingScheduleStreet::join('pubcleansingschedule_activity','pubcleansingschedule_street.pubCleansingActivityId', '=', 'pubcleansingschedule_activity.id')
->select('pubcleansingschedule_street.rowOrder')
->where('pubcleansingschedule_activity.pubCleansingScheduleParkId',$request->scheduleparkId)
->where('pubcleansingschedule_activity.activityId',$activity->id)
->orderBy('pubcleansingschedule_street.rowOrder','desc')
->limit(1)->first();
$row = $lastrow->rowOrder;
foreach ($decode as $key => $value) {
$row = $row + 1;
if($value['id'] == 0){
$schedulestreet = PubCleansingScheduleStreet::find($request->schedulestreetId);
$newsplit = new CleansingSplit;
$newsplit->pubCleansingId =$schedulestreet->pubCleansingId;
$newsplit->streetId =$schedulestreet->streetId;
$newsplit->activityCode =$schedulestreet->activityCode;
$newsplit->serviceType =$schedulestreet->serviceType;
$newsplit->value =$value['value'];
$newsplit->frequency =$schedulestreet->frequency;
$newsplit->save();
$newstreet->pubCleansingActivityId =$schedulestreet->pubCleansingActivityId;
$newstreet->pubCleansingId =$schedulestreet->pubCleansingId;
$newstreet->streetId =$schedulestreet->streetId;
$newstreet->streetName =$schedulestreet->streetName;
$newstreet->streetType =$schedulestreet->streetType ;
$newstreet->activityCode =$schedulestreet->activityCode;
$newstreet->serviceType =$schedulestreet->serviceType;
$newstreet->value =$value['value'];
$newstreet->frequency =$schedulestreet->frequency;
$newstreet->frequency_PJ =$schedulestreet->frequency_PJ;
$newstreet->rowOrder =$row;
$newstreet->save();
}
else {
$newstreet = CleansingSplit::find($value['id']);
$newstreet->value = $value['value'];
$newstreet->save();
}
}
return response()->json($newstreet);
}
}
This is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CleansingSplit extends Model
{
//
protected $table = 'publiccleansingsplit';
protected $fillable = [
'id',
'pubCleansingId',
'streetId',
'activityCode',
'serviceType',
'value',
'frequency'
];
}
Route
Route::post('splitpembersihan/storeNewArea', ['as' => 'storeNewArea', 'uses' => 'ConfigSplitCleansingController#storeNewArea']);
And this is the ajax
$.ajax(
{
url: '{{url("splitpembersihan/storeNewArea")}}',
type: 'post',
data: {
"setNewArea": setarray,
"scheduleparkId": scheduleparkId,
"schedulestreetId": schedulestreetId,
"splitId": splitId,
"activityId" : #if(isset($schedulestreet->activityCode))"{{ $schedulestreet->activityCode}}"#endif,
"_token": token
},
success: function (data)
{
alert("success");
window.location.replace('/splitpembersihan/splitBin/'+ PubCleansingID +'/splitValueArea');
},
error: function (data)
{
alert("error");
}
});
The error is the opposite. The data is stored successfully. However, it shows the error alert instead of the success alert. And if I just press the submit button without submitting anything, it shows the success alert.
Hey having a issue with the rendering of a .erb file, in my AJAX call I make a call to my create action on rails where I validate and process the form data and sent back the completed order data as render: json which works fine.
I have a conditional that checks to see if parameter exists, it if does then the completed order data is passed back as a response via render: json
It if doesn't exists it will render a receipt page.
The problem is when I render the receipt page, the full HTML receipt page comes back as a response instead of rendering the page. Please Help!
$scope.placeOrder = function() {
var body = composeOrderBody();
var isValid = validateForm(body.order);
if(isValid) {
var orderComplete = '<%= #orderComplete %>';
var baseUrl = '<%= request.base_url %>';
console.log('Passing order object: ', body.order);
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: checkout_url,
data: {
order: body.order,
xhr_request: true
},
}).then((function(_this) {
return function(response) {
if(typeof response.data == 'undefined' || response.data == null || !response.data) {
console.log('Error: missing Order Number from Order Confirmation data.', response.data);
}
console.log('Order Confirmation response data object:' , response.data);
if(orderComplete) {
var redirectUrl = 'http://' + orderComplete
var order_params = `?oid=${response.data.oid}?cart=${response.data.cart}?total=${response.data.total}`
window.location.href = redirectUrl + order_params;
} else {
console.log('Base Url: ', baseUrl);
// window.location.href = `${baseUrl}/receipt`;
}
};
})(this));
} else {
console.log('Form Validation or Stripe Validation Failed');
}
} // end placeOrder
Rails Code
# Redirect to orderComplete URL if it's set
if !#orderComplete.blank?
puts 'orderComplete parameter is not blank'
# Sum up all the line item quantities
qty = #order.line_items.inject(0) {|sum, line_item| sum + line_item.quantity}
# Get all of the coupons (and values) into a string
coupons = #order.applied_coupons.map { |coupon| coupon.coupon }.join(',')
coupon_values = #order.applied_coupons.map { |coupon| '%.2f' % coupon.applied_value.to_f }.join(',')
order_params = {
"oid" => URI::escape(#order.number),
"cart" => URI::escape(#cart),
"total" => URI::escape('%.2f' % #order.total),
}
#redirectUrl = URI.parse(URI.escape(#orderComplete))
#redirectUrl.query = [#redirectUrl.query, order_params.to_query].compact.join('&')
#redirectUrl = #redirectUrl.to_s
if params[:xhr_request]
render json: order_params.to_json
return
end
render 'receipt_redirect', :layout => 'receipt_redirect'
else
puts 'OrderComplete Parameter is blank'
render 'receipt', :layout => 'receipt', :campaign => #campaign
end
I have a form in which I save some details and upload a file. I have a factory from which I get some data. When I use ng-file-upload the factory is undefined. Here is the code:
angular.module('tollApp')
.controller('mstrEmployeeCtrl',['Upload','$window',
function(Upload,$window,$scope,$http,$timeout,$filter,$mdToast,userDetailsFactory){
$scope.ipForHttp = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
//`userDetailsFactory` is undefined
$scope.SaveData = function(){
// $scope.dobObj = new Date($scope.Emp.EmpDoB);
if ($scope.myform.$valid && $scope.passwordEqual) {
Upload.upload({
url: '$scope.ipForHttp+"addEmployee?EmpID="+$scope.Emp.EmpID,
data:{file:file} //pass file as data, should be user ng-model
})
.then(function(response){
$scope.error=response.data.code;
console.log(JSON.stringify(response));
console.log($scope.error+" SCOPE");
})
$scope.submitted = false;
}
};
}
]);
The error:
angular.min.js:117 TypeError: Cannot read property 'getUserDetailsFromFactory' of undefined
at new <anonymous> (http://192.168.1.19/public/javascripts/mstrEmployeeCtrl.js:4:38)
at Object.instantiate (http://192.168.1.19/public/javascripts/angular.min.js:41:477)
at http://192.168.1.19/public/javascripts/angular.min.js:90:3
at Object.link (http://192.168.1.19/node_modules/angular-route/angular-route.min.js:7:274)
at http://192.168.1.19/public/javascripts/angular.min.js:16:230
at ia (http://192.168.1.19/public/javascripts/angular.min.js:81:35)
at n (http://192.168.1.19/public/javascripts/angular.min.js:66:176)
at g (http://192.168.1.19/public/javascripts/angular.min.js:58:429)
at http://192.168.1.19/public/javascripts/angular.min.js:58:67
at http://192.168.1.19/public/javascripts/angular.min.js:62:430 <div data-ng-view="" class="ng-scope" data-ng-animate="1">
The factory which is undefined:
angular.module('tollApp')
.controller('indexController', function($scope,$http,$window,userDetailsFactory){
$scope.usernameFromServer={};
$scope.getUserDetails = function(){
$http({
method:'GET',
url:'http://192.168.1.19:80/getUserDetails'
})
.then(function(response){
// console.log(JSON.stringify(response));
userDetailsFactory.setUserDetailsInFactory(response.data);
$scope.usernameFromFactory = userDetailsFactory.getUserDetailsFromFactory().usernameFromSession;
// $scope.usernameFromServer = userDetailsFactory.getUserDetailsFromFactory().username;
// console.log(JSON.stringify($scope.usernameFromFactory)+"usernameFromFactory");
})
}
$scope.logout = function(request,response){
$http({
method:'GET',
url:'/logout'
})
.then(function(response){
console.log(JSON.stringify(response));
if(response.data=="logout"){
$window.location.href="http://192.168.1.19:80/login";
}
})
}
console.log("indexController");
}).factory('userDetailsFactory',function(){
var user = {};
return {
setUserDetailsInFactory : function(val){
user.useridFromSession = val[0].UserID;
user.usernameFromSession = val[0].UserName;
user.userroleFromSession = val[0].UserRole;
user.clientidFromSession = val[0].ClientID;
user.ipAddress = "http://192.168.1.19:80/";
// user.ipAddress = "http://easypaytoll.com/";
// console.log("in set "+user.clientidFromSession);
},
getUserDetailsFromFactory : function(){
return user;
}
};
});
It's an injection problem.
You have to put the userDetailsFactory in the array :
angular.module('tollApp')
.controller('mstrEmployeeCtrl',['Upload','$window','$scope', '$http','$timeout','$filter','$mdToast','userDetailsFactory'
function(Upload,$window,$scope,$http,$timeout,$filter,$mdToast,userDetailsFactory){
Edit 1
Your error is clear : userDetailsFactory is not defined. How did you define this factory ? Is it in the same module ? If not, did you add its module to the app's module dependencies ?