Load data to form using AngularJS - javascript

I am trying to load data from a Service to a form but is not binding to the field value the data loaded from the service/server:
The data from service is coming OK, the problem is after setting here in this code, I load a route to my form but the form keeps with the old values, this code is in my controller:
$scope.cadastro = {
email: '',
name: 'the name to put in the field',
city: ''
};
$scope.editar = function () {
myAppServices.getUserData($rootScope.uid).then(function (data) {
if (data !== null) {
$scope.cadastro = data;
$scope.cadastro.name = data.name;
$location.path('cadastro');
}
});
};
the HTML form:
<form name="myDataForm" class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="email">Email</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" class="form-control" placeholder="Email" name="email" ng-model="cadastro.email" focus/>
<span ng-show="myDataForm.email.$error.email" class="help-inline">Email is not valid</span>
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="name">Nome Completo</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" name="name" class="form-control" placeholder="Nome" ng-model="cadastro.name" />
<small class="errorMessage" data-ng-show="myDataForm.name.$dirty && myDataForm.name.$error.required"> Informe seu nome completo.</small>
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label no-padding-right" for="address">Cidade</label>
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="text" class="form-control" placeholder="Cidade" ng-model="cadastro.city" />
</span>
</div>
</div>
<div class="form-group">
<span class="lbl col-sm-5"> </span>
<div class="col-sm-7">
<button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="salvarcadastroForm(cadastro)" data-ng-disabled="myDataForm.$invalid">
<i class="fa fa-floppy-o"></i> Save
</button>
</div>
</div>
</form>
What should I do?
SOLUTION:
Load user data in a init method in the controller:
$scope.init = function () {
$scope.reset();
// if user logged then load data
if ($rootScope.uid !== undefined) {
myAppServices.getUserData($rootScope.uid).then(function (data) {
if (data !== null) {
$scope.formData = data;
}
});
}
};

Related

How to add multiple sections[] and subfeilds[] inside fields[] in vue js html?

How to add multiple sections[] and subfields[] inside fields[]?
My HTML form:
<div class="col-md-12 mr-auto" id="regBox">
<form class="form" method="POST" v-on:submit.prevent="handelSubmit($event);">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">room</i>
</span>
</div>
<select class="form-control" v-model="type" name="type" required="">
<option value="" selected disabled hidden>Choose Type here</option>
<option value="option">option</option>
<option value="text">text</option>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">account_circle</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Rule Name" v-model="text" required="" maxlength="20">
</div>
</div>
<div class="card-content" v-for="(bok, index) in feilds" :key="index">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Name..." v-model="bok.name" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Section..." v-model="bok.sections[0]" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="material-icons">face</i>
</span>
</div>
<input type="text" class="form-control" placeholder="Name..." v-model="bok.subfeilds[0].name" required="">
</div>
</div>
<h3>The JSON value of <code>bok</code></h3>
<textarea rows="3" cols="75%" readonly>{{ JSON.stringify(bok) }}</textarea>
</div>
<a #click="addNewRules">Add Another Rule</a>
<div class="text-center">
<button class="btn btn-primary btn-round">Get Started</button>
</div>
</form>
</div>
VueJS code:
regBox = new Vue({
el: "#regBox",
data: {
type:'',
text:'',
feilds : [{
name : null,
sections:[null],
subfeilds : [{name:null}],
}],
},
methods: {
addNewRules: function() {
this.feilds.push({ name : null,
sections:[null],
subfeilds : [{name:null}],
});
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['feilds'] = this.feilds;
data['type'] = this.type;
data['text'] = this.text;
$.ajax({
url: 'http://localhost:4000/add/act/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Registration Success");
}
else {
alert("Registration Failed");
vm.response = e;
}
}
});
return false;
},
},
});
My problem arises when I add fields[]. sections[] should be an array so, how can I add multiple sections inside fields . Also how can I add multiple subfields inside the fields[].
The code provided was perfectly working. The only issue is that I am not able to have multiple sections[] and subfields[], which is required.
<form class="form" method="POST" v-on:submit.prevent="handelSubmit($event);"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">room</i> </span> </div> <select class="form-control" v-model="type" name="type" > <option value="" selected disabled hidden>Choose Type here</option> <option value="option">option</option> <option value="text">text</option> </select> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">account_circle</i> </span> </div> <input type="text" class="form-control" placeholder="Rule Name" v-model="text" maxlength="20"> </div> </div> <div class="card-content" v-for="bok in feilds"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Username..." v-model="bok.name" > </div> </div> <div v-for="child in bok.subfeilds"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Offences..." v-model="child.name" > </div> </div> </div> <a class="btn btn-success" #click="addChild(bok)">Add Offence</a> <div v-for="(secure,index) in bok.sections"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="material-icons">face</i> </span> </div> <input type="text" class="form-control" placeholder="Section..." v-model="bok.sections[index]" > </div> </div> </div> <a class="btn btn-success" #click="addSection(bok)">Add</a> <h3>The JSON value of <code>bok</code></h3> <textarea rows="3" cols="75%" class="form-control" readonly>{{ JSON.stringify(bok) }}</textarea> </div> <a #click="addNewRules">Add Another Rule</a> <div class="text-center"> <button class="btn btn-primary btn-round">Get Started</button> </div> </form>
regBox = new Vue({
el: "#regBox",
data: {
type:'',
text:'',
feilds : [{
name : null,
sections:[],
subfeilds : [{name:null}],
}],
},
methods: {
addNewRules: function() {
this.feilds.push({ name : null,
sections:[],
subfeilds : [{name:null}],
});
},
addChild: function(bok) {
bok.subfeilds.push({});
},
addSection: function(bok) {
bok.sections.push({});
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['feilds'] = this.feilds;
data['type'] = this.type;
data['text'] = this.text;
$.ajax({
url: 'http://localhost:4000/add/act/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert("Registration Success");
}
else {
alert("Registration Failed");
vm.response = e;
}
}
});
return false;
},
},
});
I have added loops in each case. Just check this was what you expected

ng-if not working after clicking "Save Changes" button

I am trying to update information clicking on edit change button. After updating the information, I want the updated information to be shown by hiding the form, when I click on Save Changes button. My api is working and information is getting updated.But ng-if is not working after clicking Save Changes button.
info.html file
<div class="panel-body" ng-if="userEnteredInfo">
<div class="form-group">
<dl class="dl-horizontal form-info-table">
<dt>First Name:</dt>
<dd>{{user.basicInfo.firstName}}
</dd>
<dt>Last Name:</dt>
<dd>{{user.basicInfo.lastName}}</dd>
<dt>Status:</dt>
<dd>{{user.basicInfo.status}}</dd>
<dt>Work Location:</dt>
<dd>{{user.basicInfo.workLocation}}</dd>
<dt>Date of Birth:</dt>
<dd>{{user.basicInfo.dateOfBirth}}</dd>
<dt>Title:</dt>
<dd>{{user.basicInfo.title}}</dd>
</dl>
</div>
</div>
<div class="panel-body form-panel-box" ng-if="makeChanges" ng-submit="saveChanges(user)">
<form class="form-horizontal edit-changes-form">
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">First Name:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="firstName" ng-model="user.basicInfo.firstName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="lastName">Last Name:
</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="lastName" ng-
model="user.basicInfo.lastName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="status">Status:
</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="status" ng-
model="user.basicInfo.status">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="Work Location">Work
Location:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="work" ng-
model="user.basicInfo.location">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="dateOfBirth">Date of
Birth</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="dateOfBirth" ng-
model="user.basicInfo.dateOfBirth">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-3">
<input type="text/number" class="form-control" id="title"
ng-model="user.basicInfo.title">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<button type="submit" class="btn btn-default">Save
Changes</button>
</div>
</div>
</form>
info.js file
app.controller('info',function($scope,$localStorage,authService,$http){
$scope.user = $localStorage.userObject;
$scope.userEnteredInfo = true;
$scope.editChanges = function(){
$scope.makeChanges = true;
$scope.userEnteredInfo= false;
}
//Edit changes for updating information//
$scope.saveChanges = function(userData){
$scope.updatedInfoDetails = {
firstName: userData.basicInfo.firstName,
lastName: userData.basicInfo.lastName,
status: userData.basicInfo.status,
WorkLocation: userData.basicInfo.location,
dateOfBirth: userData.basicInfo.dateOfBirth,
title: userData.basicInfo.title
}
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
};
});
$scope.userEnteredInfo = false;
$scope.makeChanges = true;
console.log("success");
};
});
authService.js file
app.service('authService', function($localStorage,$http) {
this.postUpdatedInfo = function(userChangedInfo){
console.log('the user data is: ', userChangedInfo);
var urlForChangingInfo = "/api/users/" + $localStorage.getUserId;
return $http({
method:'PUT',
url:urlForChangingInfo,
data:userChangedInfo,
headers:{"x-access-token":$localStorage.authToken}
});
};
});
makeChanges is never made to false,
try this,
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
};
});
$scope.userEnteredInfo = false;
$scope.makeChanges = false;
console.log("success");
};
you are never setting $scope.userEnteredInfo to true , can you try code given below :
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
$scope.userEnteredInfo = true;//set true here
$scope.makeChanges = true;
console.log("success");
}
else
{
// error if response status other than 200
$scope.userEnteredInfo = false;
$scope.makeChanges = false;
console.log("error");
};
});
};

Error: [ng:areq] Argument 'UsersSettingsController' is not a function, got undefined

I'm trying to create a edit profile section in angularjs. For that i create in my users controller a section to make a rest api call to get info to inject on the page and later i will do the parte of changePassword also.
At the moment i'm getting the error "Error: [ng:areq] Argument 'UsersSettingsController' is not a function, got undefined" and I cant undestand why.
editAccount view:
<div class="row" ng-controller="UsersSettingsController as usersSettingsCtrl" >
{{userInfo}}
<!-- edit form column -->
<div class="col-md-9 personal-info">
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.username}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Organization:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.organization_name}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Permission Group:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.permission_group_name}}" readonly>
</div>
</div>
<div class="form-group" nf-ig="user.organization_permission_group_id=='df0417e3-ce36-41ca-9f13-f58c1a3a96f5'">
<label class="col-lg-3 control-label">Root:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.data.root}}" readonly>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" style="background-color: #fff" value="{{userInfo.username}}" readonly>
</div>
</div>
<hr>
<h4>Change Password</h4>
<br>
<form name="newPasswordForm" role="form" ng-submit="newPasswordForm.$valid && ok()" novalidate>
<div class="form-group">
<label class="col-md-3 control-label">Change Password:</label>
<div class="col-md-8">
<input type="password" name="newPassword" ng-model="password.new"
ng-minlength="6" required />
<span class="help-block"
ng-show="newPasswordForm.newPassword.$dirty && newPasswordForm.newPassword.$invalid">
Please enter a new password, it must be at least 6 characters long.
</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Confirm password:</label>
<div class="col-md-8">
<input type="password" name="newPasswordConfirm"
ng-model="password.confirm" ng-minlength="6"
value-matches="password.new" required />
<span class="help-block"
ng-show="newPasswordForm.newPasswordConfirm.$dirty && newPasswordForm.newPasswordConfirm.$invalid">
Please enter the same password again to confirm.
</span>
</div>
</div>
</form>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input type="button" class="btn btn-primary" style="float:right" value="Save Changes">
<div ng-messages="registrationForm.confirmPassword.$error" ng-messages-include="messages.html"></div>
</div>
</div>
</form>
</div>
</div>
usersController:
app.controller('UsersSettingsController',['$scope', 'user', function ($scope, user) {
$http.get('/api/users/userInfo/'+user.id).success(function (data) {
console.log("user info ",data);
$scope.userInfo = data;
});
//changePassword call to rest api
}]);
usersDirective:
(function() {
var app = angular.module('userSettings', []);
app.directive('valueMatches', ['$parse', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModel) {
var originalModel = $parse(attrs.valueMatches),
secondModel = $parse(attrs.ngModel);
// Watch for changes to this input
scope.$watch(attrs.ngModel, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === originalModel(scope));
});
// Watch for changes to the value-matches model's value
scope.$watch(attrs.valueMatches, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === secondModel(scope));
});
}
};
}]);
})();

JQUERY AJAX POST ERROR 500 any idea? I'm trying to insert records into

CODEIGNITER METHOD
public function agregar_post(){
$nombre = $this->post('nombre');
$mail = $this->post('mail');
$telefono = $this->post('telefono');
$password = $this->post('password');
$nivel_listado = $this->post('nivel_listado');
// Store he whole data into $data
$data = array(
'id' => '',
'nombre' => $nombre,
'mail' => $mail,
'telefono' => $telefono,
'password' => $password,
'api_key' => '',
'nivel_listados' => $nivel_listado
);
$query = $this->db->insert('cliente',$data);
// Check if insert is succes
if ($query)
{
$this->output->set_header("Access-Control-Allow-Origin: http://www.verdulero.com", false); // header allow
$this->response($query,201);
}else
{
$this->response(null,404);
}
}
//JQUERY AJAX
$("#frmAddClient").submit(function (event){
event.preventDefault();
var dataForm = $(this).serialize();
// ajax to insert a new product
$.ajax({
type: $(this).attr('method'), // METHOD FROM FORM
url: $(this).attr('action'), // URL FROM FORM
crossDomain: true,
data: dataForm,
success: function(){
alert();
}
});
// CLEAN THE FORM AFTER INSERT
$("#frmAddClient")[0].reset();
});
// HTML
<form name="frmAddClient" id="frmAddClient" method="post" action="<?= $addClient ?>" class="form-horizontal">
<div class="form-group">
<label for="Email" class="col-sm-4 control-label">Correo electronico:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="text" class="form-control" id="Email" name="mail" placeholder="Verdulero#example.com" value="" autofocus required>
</div>
</div>
</div>
<div class="form-group">
<label for="Nombre" class="col-sm-4 control-label">Nombre:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="Nombre" name="nombre" placeholder="Juan Verdura" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Telefono" class="col-sm-4 control-label">Telefono:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-phone-alt"></span></span>
<input type="text" class="form-control" id="Telefono" name="telefono" placeholder=" 555 555 555" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Password" class="col-sm-4 control-label">Password:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" id="Password" name="password" placeholder="Password" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="nivel_listado" class="col-sm-4 control-label">Nivel Listado:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<select class="form-control" name='nivel_listado' id='nivel_listado'>
<option value=''>Elija</option>
<option value='1'>Usuario nivel 1</option>
<option value='2'>Usuario nivel 2</option>
<option value='3'>Usuario nivel 3</option>
<option value='4'>Nivel administrador</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<input type="submit" class="btn btn-success" name="submit" id="Submit_User" value="Insertar nuevo usuario"/>
</div>
</div>
</form>
Use $this->input->post() instead of $this->post()
$nombre = $this->input->post('nombre');
$mail = $this->input->post('mail');
$telefono = $this->input->post('telefono');
$password = $this->input->post('password');
$nivel_listado = $this->input->post('nivel_listado');

$window.location is not working in ipad only with angular js

**my angular function **
self.login = function () {
loginService.login(self.user).success(function (response) {
sessionService.set("token", response.response.token);
$window.location.href = "/camera";
}).error(function (response) {
flashService.showError(response.message);
});
}
my html code
<form name="myForm" class="row" ng-submit = loginCtrl.login() novalidate>
<label>Username or email</label>
<div class='form-group' ng-class="{ 'has-error' : myForm.userName.$invalid && !myForm.userName.$pristine }">
<input type="text" name="userName" class="input-block-level form-control" placeholder="Your username or email" ng-model = "loginCtrl.user.email" required/>
<p ng-show="myForm.userName.$invalid && !myForm.userName.$pristine" class="help-block">Please enter the username or email.</p>
</div>
<label >Password <a class="password" href="javascript:void(0)" data-toggle="modal" ng-click="loginCtrl.openForgetPasswordModal('md')" >forgot it?</a></label>
<div class='form-group' ng-class="{ 'has-error' : myForm.password.$invalid && !myForm.password.$pristine }">
<input type="password" name= "password" class="input-block-level form-control margin-none" placeholder="Your password" ng-model = "loginCtrl.user.password" required/>
<p ng-show="myForm.password.$invalid && !myForm.password.$pristine" class="help-block">Please fill up the password.</p>
</div>
<div class="separator bottom"></div>
<div class="col-md-8 padding-none ">
<div class="uniformjs"><label class="checkbox theme-color"><input type="checkbox" value="remember-me" ng-model = "loginCtrl.remember" ng-click="loginCtrl.rememberMe()"remember-me>Remember me</label>
</div>
</div>
<div class="col-md-4 pull-right padding-none">
<button class="btn btn-block btn-primary" type="submit">Sign In</button>
</div>
</form>
I want when i click on login button then it will be redirect on seprate page.but window location is not working here.
use this:
$location.path('/camera');

Categories

Resources