Not able to pass value in angular function - angularjs

I am trying to pass expense object to submit function.
But it is not passing entered value
var app = angular.module('addApp', []);
app.controller('addController', function($scope, $http) {
console.log("SAdfasd");
$scope.expense = {param:'',value:0,dt:'',description:''};
$scope.exp = ["One ", "Two", "Three"];
$scope.submit = function(data) {
console.log(data);
console.log($scope.expense);
$http({
method: 'POST',
url: 'added'
data: $scope.expense,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, header, config) {
console.log(data);
}
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
<div class="col-lg-8 col-md-8" ng-app="addApp" ng-controller="addController">
<form id="addExpense" name="expenseForm" method="post">
<div>
<label>Expense Type</label>
<select ng-model="expense.param" ng-options="x for x in exp" class="form-control"></select>
</div>
<div>
<label>Amount</label>
<input type="text" name="value" class="form-control" ng-bind="expense.value" placeholder="Enter your expense amount" />
</div>
<div>
<label>Date</label>
<input type="date" name="dt" class="form-control" ng-bind="expense.dt" placeholder="Select expense date" />
</div>
<div>
<label>Description</label>
<textarea rows="4" cols="50" name="description" ng-bind="expense.description" class="form-control" placeholder="Enter your expense description"></textarea>
</div>
<div>
<button type="submit" class="btn btn-success form-control" ng-click="submit(expense)">Save</button>
</form>
</div>

You are using NgBind instead of that it should be NgModel :
var app = angular.module('addApp', []);
app.controller('addController', function($scope, $http) {
$scope.expense=
{param:'',value:0,dt:'',description:''};
$scope.exp = ["One ", "Two", "Three"];
$scope.submit = function() {
//console.log(object);
console.log($scope.expense);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
<div class="col-lg-8 col-md-8" ng-app="addApp" ng-controller="addController">
<form id="addExpense" name="expenseForm" method="post">
<div>
<label>Expense Type</label>
<select ng-model="expense.param" ng-options="x for x in exp" class="form-control"></select>
</div>
<div>
<label>Amount</label>
<input type="text" name="value" class="form-control" ng-model="expense.value" placeholder="Enter your expense amount" />
</div>
<div>
<label>Date</label>
<input type="date" name="dt" class="form-control" ng-model="expense.dt" placeholder="Select expense date" />
</div>
<div>
<label>Description</label>
<textarea rows="4" cols="50" name="description" ng-model="expense.description" class="form-control" placeholder="Enter your expense description"></textarea>
</div>
<div>
<button type="submit" class="btn btn-success form-control" ng-click="submit(expense)">Save</button>
</form>
</div>

You are sending JSON obejct to your action but it is expecting it in a Url Params. You can refer your query from here ParamSerializer.
So angular provide $httpParamSerializerJQLike service since 1.4.1
$http({
url: 'added',
method: 'POST',
data: $httpParamSerializerJQLike(data), // Make sure to inject the
service in to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // header
}
}).then(function(response) { /* do something here */ });
Second way to do -
$http({
url: 'added',
method: 'POST',
data: 'param='+$scope.expense.param+'&value='+$scope.expense.value+'& dt='+$scope.expense.dt+ '& description='+$scope.expense.description OR 'param='+encodeURIComponent($scope.expense.param)+'&value='+encodeURIComponent$scope.expense.value)+'& dt=+encodeURIComponent$scope.expense.dt)+ '& description='+encodeURIComponent$scope.expense.description)
service in to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // header
}
}).then(function(response) { /* do something here */ });
Please check the syntax's for comma i might have missed .

Related

Showing json data in textbox

I want to show json data to text box. but it is not showing in text box
my code is
var app = angular.module('productApp', []);
app.controller('productController', function($scope, $http) {
var x = 1054;
alert(x);
$http({
method: 'GET',
url: 'getProduct',
params: {
id: x
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response, status, headers, config) {
console.log(response);
$scope.products = response;
})
.error(function(data, status, headers, config) {
alert("Opps unable to connect to server");
});
}); <
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div class="container">
<div class="all-data" ng-app="productApp" ng-controller="productController">
<form id="updateProduct" action="UpdatedProduct" method="post">
<legend>Update Product</legend>
<div class="products" ng-repeat="p in products">
{{p.id}}{{p.unitPrice}}
<input type="hidden" ng-model="p.id" />
<label>Bar Code</label>
<input type="text" name="barCode" class="form-control" id="barCode" ng-model="p.barcode" />
<label> Quantity </label>
<input type="text" name="quantity" ng-model="p.quantity" class="form-control" id="quantity" />
<label>Unit Price</label>
<input type="text" name="unitPrice" ng-model="p.unitPrice" class="form-control" id="unitPrice" />
<label>Selling Price</label>
<input type="text" name="sellingPrice" class="form-control" id="sellingPrice" ng-model="p.sellingPrice" data-validation="required" data-validation-error-msg="Selling price required" />
<label>Discount Percentage</label>
<input type="text" name="discountPercentage" class="form-control" id="discountPercentage" ng-model="p.discountPercentage" />
<label>Tax1</label>
<input type="text" name="tax1name" class="form-control" id="tax1name" ng-model="p.tax1.name" />
<input type="hidden" name="tax1id" class="form-control" id="tax1id" ng-model="p.tax1.id" />
<input type="hidden" name="tax1value" class="form-control" id="tax1val" ng-model="p.tax1.value" />
<label>Tax2</label>
<input type="text" name="tax2name" class="form-control" id="tax2name" ng-model="p.tax2.name" />
<input type="hidden" name="tax2id" class="form-control" id="tax2id" ng-model="p.tax2.id" />
<input type="hidden" name="tax2value" class="form-control" id="tax2val" ng-model="p.tax2.value" />
<button type="submit" class="form-control btn btn-success" style="margin-top: 10px" ng-click="update(p)">Update</button>
</div>
</div>
my json data is
{"productList":[{"discountPercentage":3,"id":1054,"quantity":234,"sellingPrice":555.00,"tax1id":0,"tax1value":0,"tax2id":0,"tax2value":0,"unitPrice":234.00}]}
Try this one
}).success(function(response, status, headers, config) {
console.log(response);
$scope.products = response.productList;
})
Use response.data.productList,
$http({
method: 'GET',
url: 'getProduct',
params: {
id: x
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response, status, headers, config) {
console.log(response);
$scope.products = response.data.productList;
})
.error(function(data, status, headers, config) {
alert("Opps unable to connect to server");
});
You either need to iterate over products.productList or, assign $scope.products = response.productList.
Here's working example: (I have used $timeout to simulate API call)
var app = angular.module('productApp', []);
app.controller('productController', function($scope, $timeout) {
var x = 1054;
alert(x);
$timeout(function() {
$scope.products = {
"productList": [{
"discountPercentage": 3,
"id": 1054,
"quantity": 234,
"sellingPrice": 555.00,
"tax1id": 0,
"tax1value": 0,
"tax2id": 0,
"tax2value": 0,
"unitPrice": 234.00
}]
}
}, 1000)
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div class="container">
<div class="all-data" ng-app="productApp" ng-controller="productController">
<form id="updateProduct" action="UpdatedProduct" method="post">
<legend>Update Product</legend>
<div class="products" ng-repeat="p in products.productList">
{{p.id}}{{p.unitPrice}}
<input type="hidden" ng-model="p.id" />
<label>Bar Code</label>
<input type="text" name="barCode" class="form-control" id="barCode" ng-model="p.barcode" />
<label> Quantity </label>
<input type="text" name="quantity" ng-model="p.quantity" class="form-control" id="quantity" />
<label>Unit Price</label>
<input type="text" name="unitPrice" ng-model="p.unitPrice" class="form-control" id="unitPrice" />
<label>Selling Price</label>
<input type="text" name="sellingPrice" class="form-control" id="sellingPrice" ng-model="p.sellingPrice" data-validation="required" data-validation-error-msg="Selling price required" />
<label>Discount Percentage</label>
<input type="text" name="discountPercentage" class="form-control" id="discountPercentage" ng-model="p.discountPercentage" />
<label>Tax1</label>
<input type="text" name="tax1name" class="form-control" id="tax1name" ng-model="p.tax1.name" />
<input type="hidden" name="tax1id" class="form-control" id="tax1id" ng-model="p.tax1.id" />
<input type="hidden" name="tax1value" class="form-control" id="tax1val" ng-model="p.tax1.value" />
<label>Tax2</label>
<input type="text" name="tax2name" class="form-control" id="tax2name" ng-model="p.tax2.name" />
<input type="hidden" name="tax2id" class="form-control" id="tax2id" ng-model="p.tax2.id" />
<input type="hidden" name="tax2value" class="form-control" id="tax2val" ng-model="p.tax2.value" />
<button type="submit" class="form-control btn btn-success" style="margin-top: 10px" ng-click="update(p)">Update</button>
</div>
</div>

ng-file upload not sending file along with other data

i am using angular js frontend along with ng-file module and laravel backend, and for some reason unknown, ng fileupload doesn't send file along with other form data:
here is my form:
<form method="post" name="myForm">
<div class="form-group has-feedback">
<input type="file" ngf-select ng-model="picFile" name="file"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<i ng-show="myForm.file.$error.required">*required</i><br>
<i ng-show="myForm.file.$error.maxSize">File too large
{{errorFile.size / 1000000|number:1}}MB: max 2M</i>
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb"> <button ng-click="picFile = null" ng-show="picFile">Remove</button>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" id="username" type="text" name="username" ng-model="user.username" placeholder="Name"
required
ng-minlength="6"
autofocus>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="email" id="email" name="email" ng-model="user.email" placeholder="Email" required>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="text" id="firstname" name="firstname" ng-model="user.firstname" placeholder="First Name">
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="text" id="lastname" name="lastname" ng-model="user.lastname" placeholder="Last Name">
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary" ng-disabled="!myForm.$valid" ng-click="updateProfile(picFile)" >Update</button>
<span class="progress" ng-show="picFile.progress >= 0">
<div style="width:{{picFile.progress}}%"
ng-bind="picFile.progress + '%'"></div>
</span>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
{{picFile}}
</form>
and here is my controller:
$scope.getProfile = function() {
Account.getProfile()
.then(function(response) {
$scope.user = response.data;
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
$scope.updateProfile = function(file) {
file.upload = Upload.upload({
url: '/kilo/api/me',
data: {username: $scope.user.username, file: file },
method:"POST"
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data.message;
console.log(file.result);
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
};
the above sends only the "username" and leaves the file. please can anyone show me what am doing wrong?
Add arrayKey: '', headers: { 'Content-Type': undefined }, to your upload object.

Angular js Update a div without updating the whole page

Please i want to update a specific div in my view instead of reloading the whole page.
This is my Script.
$scope.submitComment = function() {
$http({
url: "comment",
method: "POST",
data: $.param($scope.commentData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
$scope.loading = true;
//location.reload();
$scope.loading = false;
}).error(function(response) {
console.log(response);
alert('Sorry an error occured');
});
};
This is my view
<div ng-controller="myController">
<br> <br> <br> <br>
<form ng-submit="submitComment()" id="form">
<div class="form-group">
<label for="author">Author: </label>
<input id="author" class="form-control " type="text" ng-model="commentData.author" name="author" placeholder="Enter author">
</div>
<div class="form-group">
<label for="message">Message:</label> #{{ commentData.message }}
<textarea id="message" class="form-control" ng-model="commentData.message" name="message" placeholder="Enter Comment" rows="8" cols="40"></textarea>
</div>
<div class="form-group pull-right">
<button type="submit" class="btn btn-primary"><i class="fa fa-comment-o"> Comment</i></button>
<!-- <input class="btn btn-primary" type="submit" value="Comment"> -->
</div>
</form>
<h2>Comments</h2> <hr>
<div ng-repeat="comment in comments">
<div><strong>#{{ comment.author }}</strong></div>
<div>#{{ comment.message }} <button type="button" ng-click="deleteComment(comment.id)" class="btn btn-danger-outline btn-sm" id="submit">Delete</button></div>
<br>
</div>
</div>
I want to update my form so that the text in it goes. and also update my comments as well. I need a help on this please.
In your $scope.submitComment() method, $http.success(), you need to $scope.comments.push($scope.commentData) and you should be good to go.
$scope.submitComment = function() {
$http({
// ...
}).success(function(response) {
$scope.comments.push($scope.commentData);
});
};

AngularJS & Laravel - Wizard navigation

I am trying to create a multi form/wizard step navigation. I am using ng-switch to create the steps. But I got stuck, this is the relevant code:
HTML:
<div ng-controller="stepCtrl">
<div ng-switch="step">
<div ng-switch-when="1">
<div ng-controller="postAddressDataCtrl">
<form url="users/createaddress" ng-submit="add()">
<label class="input-label">
<span class="label-title">
Line 1
</span>
<input type="text" name="line-1" ng-model="line1" placeholder="Line 1">
</label>
<label class="input-label">
<span class="label-title">
Line 2
</span>
<input type="text" name="line-2" ng-model="line2" placeholder="Line 2">
</label>
<label class="input-label">
<span class="label-title">
City
</span>
<input type="text" name="city" ng-model="city" placeholder="City">
</label>
<label class="input-label">
<span class="label-title">
Postcode
</span>
<input type="text" name="postcode" ng-model="postcode" placeholder="Postcode">
</label>
<label class="input-label">
<span class="label-title">
Country
</span>
<input type="text" name="country" ng-model="country" placeholder="Country">
</label>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
{{ Form::button('Save Address', array('type'=>'submit', 'class'=>'btn btn-primary', 'style' => 'width:100%;')) }}
</div>
</form>
</div>
<button ng-click="setStep(2)">Step 2</button>
</div>
<div ng-switch-when="2">
Step 2 - another form
<button ng-click="setStep(1)">Step 1</button>
<button ng-click="setStep(3)">Step 3</button>
</div>
<div ng-switch-when="3">
Step 3 - another form
<button ng-click="setStep(2)">Step 2</button>
</div>
</div>
</div>
Controllers:
stepCtrl
myApp.controller('stepCtrl',function($scope){
$scope.step = 1;
$scope.setStep = function(step){
$scope.step = step;
}
});
postAddressDataCtrl
myApp.controller('postAddressDataCtrl', ['$scope', '$http', 'CSRF_TOKEN', function($scope, $http, CSRF_TOKEN) {
$scope.urlpath = '{{ url('/') }}';
$scope.add = function() {
var line1 = $scope.line1;
var line2 = $scope.line2;
var city = $scope.city;
var postcode = $scope.postcode;
var country = $scope.country;
return $http({
url: "/users/createaddress",
method: "POST",
data: {
'line1': line1,
'line2': line2,
'city': city,
'postcode': postcode,
'country': country,
'_token': CSRF_TOKEN
},
}).success(function(data, status, headers, config) {
console.log(data);
if (data.status == 200) {
// move to the next step
}
}).error(function(data, status, headers, config) {
console.log(data);
});
};
}]);
How can I check if the data entered in the form are valid and if they are then to move in the next step with a single button?
How can I set the step equal to 2 when the data.status is equal to 200, so only then it will move on?
Use Angular's form validation. For example add required to your input field if you want to require the field and ng-minlength or ng-maxlength for character limits. You can also write custom validation if you need specific validation on certain fields.
To change the step you can increment your step variable inside ng-submit.
To increment only if your $http request is successful you can put it directly in your .success function.
<form url="users/createaddress" ng-submit="add()" novalidate>
<label class="input-label">
<span class="label-title">
Line 1
</span>
<input type="text" name="line-1" ng-model="line1" placeholder="Line 1" ng-minlength=3 ng-maxlength=20 required>
</label>
<button type="submit" class="btn btn-primary">Save Address</button>
</form>
postAddressDataCtrl
myApp.controller('postAddressDataCtrl', ['$scope', '$http', 'CSRF_TOKEN', function($scope, $http, CSRF_TOKEN) {
$scope.urlpath = '{{ url('/') }}';
$scope.add = function() {
var line1 = $scope.line1;
var line2 = $scope.line2;
var city = $scope.city;
var postcode = $scope.postcode;
var country = $scope.country;
return $http({
url: "/users/createaddress",
method: "POST",
data: {
'line1': line1,
'line2': line2,
'city': city,
'postcode': postcode,
'country': country,
'_token': CSRF_TOKEN
},
}).success(function(data, status, headers, config) {
console.log(data);
if (data.status == 200) {
// move to the next step
$scope.step += 1;
}
}).error(function(data, status, headers, config) {
console.log(data);
});
};
}]);

How to $http.post with payload in data?

How do I post data from a form in AngularJS?
<form data-ng-submit="doSomething()">
<input type="text" data-ng-input="do_obj.text"/>
<input type="email" data-ng-input="do_obj.email"/>
<input type="submit" value="Do something"/>
</form>
$scope.doSomething = function () {
$http({url: '/api/oauth2/register', method: 'POST', data: $scope.do_obj}
).then(function (data, status, headers, config) {
$log.info("data = ", data, "status = ", status,
"headers = ", headers, "config = ", config);
}
);
};
Plnkr (bootstrap styled)
See plunker code here
Changed data-ng-input into data-ng-model and updated data-ng-submit to pass in the model into the scope controller for processing.
HTML:
<body data-ng-app>
<div data-ng-controller="DoCtrl" class="container" style="margin: 15px">
<form data-ng-submit="doSomething(do_obj)" role="form" class="form-inline">
<div class="form-group">
<input type="text" data-ng-model="do_obj.bar"
placeholder="Enter text"
/>
</div>
<div class="form-group">
<input class="form-group" type="email"
data-ng-model="do_obj.email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<input class="btn btn-lg" type="submit"
data-ng-class="{'btn-info': hover}"
data-ng-mouseenter="hover = true"
data-ng-mouseleave="hover = false"
value="Do something"
/>
</div>
</form>
</div>
</body>
The syntax for posting is $http.post({url}, {payload});. I have updated your controller function to take in a parameter to pass to the post.
Controller code:
function DoCtrl($scope, $http, $log) {
$log.info("In DoCtrl");
$scope.do_obj = {};
$scope.doSomething = function (data) {
$http.post('/api/oauth2/register', data)
.success(function(successData){
console.log(successData);
});
}
}

Resources