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 ?
Related
I've been scratching my head about this for a while. I'm new to Vue and can't seem to understand why this isn't working.
My template...
<template>
<div>
<div v-if="loading" class="loading">Loading...</div>
<div v-if="dbhs">
<h1>adfoij</h1>
<p class="mb-0" v-if="dbhs.length === 0">
You have not any DBHs.
</p>
<div v-else>
<div v-for="dbh in dbhs">{{dbh.dbh}} - {{dbh.count}}</div>
</div>
</div>
</div>
</template>
My script...
<script>
export default {
data() {
return {
loading: true,
dbhs: null
};
},
created() {
this.getDbhs();
},
methods: {
ajaxAxiosGetFunc: async function (url) {
var output = '';
await axios({
method: 'post',
url: url,
data: {},
responseType: 'json',
})
.then(function (response) {
//output = JSON.parse(response.data);
output = response.data;
}.bind(this))
.catch(function (error) {
console.log('ajax error');
});
return output
},
getDbhs: async function(){
var estimate_id = document.getElementById('estimate_id').value
var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh'); // called asynchronously to wait till we get response back
this.dbhs = output;
console.log(output);
this.loading = false;
},
}
}
</script>
I'm getting data back from the API... it prints out in the console fine but the length of dbhs is always 0.
Anyone have any ideas?
It's because your method uses function keyword which overrides this that refers to the vue instance, change your anonymous function to an arrow function should work:
getDbhs: async () => {
var estimate_id = document.getElementById('estimate_id').value
var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh'); // called asynchronously to wait till we get response back
this.dbhs = output;
console.log(output);
this.loading = false;
},
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 dropdown list of options, which are shown or not depending on conditions.
<div class="col-sm-9">
<select class="form-control" ng-model="vm.templateType" ng-disabled="vm.status == 'sold' || vm.status == 'return' "ng-options="type.id as type.name for type in vm.templateTypes | filter:vm.isShowableTemplate"></select>
</div>
Here is my controller:
function FormOrderDialogController(tsModulesService, $scope, $q, $http, $uibModalInstance, params, $filter, Requester)
Requester.restGet("/events/" + params.eventId, null, params.serverId).then((data)=>{
vm.event = data;
});
Requester.restGet('/dic/10', null, null, null, true).then((resp) => {
vm.templateTypes = resp;
vm.templateType = vm.templateTypes[0].id;
});
vm.isShowableTemplate = isShowableTemplate;
function isShowableTemplate(templateType) {
switch (templateType.id) {
case 321:
return !!vm.event.info.ticketTemplate;
case 322:
return !!vm.event.info.ticketETemplate;
}
}
By the time isShowableTemplate is called I expect event object to be filled, And the thing is the getEvent function is called twice, once before isShowableTemplate get called, and once after. The problem is event is undefined after the first call and I get an error "Cannot read property 'info' of undefined".
My question is why is it so and what I am doing wrong. I am new to both js and angular, so may be I miss something essential.
Why not remove the function and filter:
function FormOrderDialogController(tsModulesService, $scope, $q, $http, $uibModalInstance, params, $filter, Requester)
Requester.restGet("/events/" + params.eventId, null, params.serverId)
.then(data => {
vm.event = data;
return Requester.restGet('/dic/10', null, null, null, true);
})
.then(resp => {
vm.templateTypes = resp;
vm.showableTemplateTypes = resp.filter(t => {
switch (t.id) {
case 321:
return !!vm.event.info.ticketTemplate;
case 322:
return !!vm.event.info.ticketTemplate;
}
return false; // or true depending if you want to show the others.
});
vm.templateType = vm.templateTypes[0].id;
});
}
I've combined the two Promises together because you use the vm.event in the second response. By doing it this way, you can always guarantee some value for vm.event.
The html:
<div class="col-sm-9">
<select class="form-control" ng-model="vm.templateType" ng-disabled="vm.status == 'sold' || vm.status == 'return' "ng-options="type.id as type.name for type in vm.showableTemplateTypes"></select>
</div>
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?
I'm building a simple form.
This form get a birthday field.
I can select a date and persist it.
But when I reload the page, I have an error
Error: [ngModel:datefmt] Expected `2015-03-06T23:00:00.000Z` to be a date
I know how to resolve it. I need to convert my user.date_birthday to a Date.
So I tried this.
'use strict';
angular.module('TheNameApp')
.controller('SettingsCtrl', function ($scope, User, Auth) {
$scope.user = User.get();
$scope.errors = {};
console.log($scope.user); // display the resource
console.log($scope.user.date_birthday); //undefined
$scope.changeInformations = function(form) {
$scope.infos_submitted = true;
if(form.$valid) {
Auth.changeInformations({
gender: $scope.user.gender,
city: $scope.user.city,
country: $scope.user.country,
talent: $scope.user.talent,
date_birthday: $scope.user.date_birthday,
user_name: $scope.user.user_name,
email: $scope.user.email })
.then( function() {
$scope.infos_message = 'Done.'
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
the .html
<div class="form-group">
<label>Birthday</label>
<input type="date" name="date_birthday" class="form-control" ng-model="user.date_birthday"/>
</div>
The user.date_birthday is not defined but I can see it in $scope.user
I need this for my next step
$scope.user.date_birthday = new Date($scope.user.date_birthday);
Why I can't see my attribute? How Can I resolve this?
Assuming your User is a resource, .get() is an async call. Use a callback:
User.get(function(user) {
user.date_birthday = new Date(user.date_birthday);
$scope.user = user;
});