I am pretty new in angular.
I'm working on an internal tool where I can get the user details like location, work profile and mobile number etc.
So i have a form with location, work profile dropdowns and mobile number input field. Here for the above fields im already getting data from database through ajax get request. If i want to change data like mobileNumber, how can i do that and how to save that to database which should override the before mobile number. thanks in advance.
here is my html code:
<form name="userForm">
<div class="page-heading fs-xs-1-5">
Update Profile
</div>
<div class= "second-row">
<div class="row">
<div class="col-lg-4">
<label for="Location"> Location</label>
<select class="form-control" placeholder="location" ng-model="user.location" required>
<option value="">Select Location</option>
<option>Hyderabad</option>
<option>Ahmadabad</option>
<option>New Jersey</option>
<option>California</option>
<option>Jaipur</option>
</select>
</div>
<div class="col-lg-4">
<label for="WorkProfile"> Work Profile</label>
<select class="form-control" placeholder="workprofile" ng-model="user.workProfile" required>
<option value="">Select Profile</option>
<option>UI Developer</option>
<option>Tester</option>
</select>
</div>
<div class="col-lg-4">
<label for="ContactNumber"> Contact Number</label>
<input class="form-width contact-height" type="text" ng-model="user.mobileNumber" maxlength="20" required></input>
</div>
</div>
</div>
<div class="third-row">
<div class="row">
<div class="col-lg-4">
<label for="SkillSet"> Skill Set</label>
<textarea id="SkillSet" class="form-width" placeholder="Enter Your skill set here..." row="4" col="100" ng-model="user.skillset" maxlength="250" required></textarea>
</div>
</div>
</div>
<button class="btn btn-primary setng-btn" type="submit" ng-click="addnewdata">Save</button>
</form>
js:`
(function () {
angular
.module('app.login')
.factory('userprofileService', userprofileService);
userprofileService.$inject = ['config', '$http'];
function userprofileService (config, $http) {
var userprofileService = this;
userprofileService.getUserDetails = function(){
return $http({
method: 'GET',
url: config.apiURL+'/v2/user',
headers: { 'Content-Type': 'application/json' }
}).then(function(response){
return response.data;
});
}
`
That will be too much to make clear.
for short, you need REST service as backend to call to save data.
AngularJS project is only front-end, you need backend ( to develop with Nodejs, JSP or asp.net/C# ) to serve this purpose.
Related
I am using AngularJS. I would like to send multiple data in a HTTP post through AngularJS.I am using laravel php as backend and tinymce as my html text editor.The problem is that tinymce comes up with a model and i am unable to figure it out on how to pass data that is dealing with multiple models.
Here is my partial:
<div ng-controller="controller">
<div class="row">
<div class="container">
<div class="col-lg-8">
<form role="form" method="post" >
<div class="form-group" >
<input type="text" class="form-control" name="" ng-model="post.title" placeholder="Type the title here">
</div>
<div action="" class="form-group" ng-controller="TinyMceController">
<textarea ui-tinymce="tinymceOptions" ng-model="tinymceModel" style="height:300px">
</textarea>
</div>
<div class="form-group">
<input type="text" class="form-control" id="" ng-model="post.tags" placeholder="Atleast one related tag">
</div>
<button type="submit" class="btn btn-primary" ng-click="postsave()">Submit</button>
<button class="btn btn-default">Discard</button>
</form>
</div>
<div class="col-lg-4">
RULES:
</div>
</div>
</div>
my controller:
app.controller('controller',['$scope','$rootScope','$http',function($scope,$rootScope,$http){
$scope.post={
title:"",
};
$scope.postsave= function(){
$http({
method:"POST",
url:'http://localhost/../../...',
data: //I can pass title by using $scope.title but i aslo
//want to pass $scope.tinymcemodel
})
.success(function(result){
alert(result);
})
}
Any help would be great.Also suggest me if there is a better way of doing it.
Thank you.
Just like your post.tags is structured, you should do the same. Put all your children under a parent and submit the parent. Let's look at that:
$scope.formData = {}; //parent
Then your textarea/title should be altered accordingly:
ng-model="formData.title" //child
ng-model="formData.tinymcemodel" //child
And then when you pass your data over, you can just pass this.formData.
$scope.postsave= function(){
$http({
method:"POST",
url:'http://localhost/../../...',
data: this.formData
})
.success(function(result){
alert(result);
})
};
This will properly send over the object to the server, which will have the key:value pairs as your title and tinymcemodel. Note that post.tags won't be included in this submission given that it belongs to another parent.
I'm a beginner and I'm creating a simple CRUD system using AngularJS and Laravel 5. I'm having problems implementing/making the UPDATE feature (to edit data) work. Every time I run it, I keep getting this error on my browser console:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mycrudapp-kkoyao.c9users.io' is therefore not allowed access. The response had HTTP status code 500.*
Here is my code for my html/form:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="addApp" ng-controller="addController">
<h2>Edit Account</h2>
<h4 class="modal-title" id="myModalLabel">Please fill in details</h4>
<div class="modal-body">
<form name="frmAccounts" ng-submit="submitForm(Account.id)" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputEmail3" class="col-sm-3 control-label">Account Holder's Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Enter First and Last Name"
ng-model="Account.acctName" ng-required="true">
<span class="help-inline"
ng-show="frmAccounts.name.$invalid && frmAccounts.name.$touched">Name field is required.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctNum" name="acctNum" placeholder="Enter Bank Account Number"
ng-model="Account.acctNum" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctNum.$invalid && frmAccounts.acctNum.$touched">Please check your Bank Account Number.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Type</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctType" name="acctType" placeholder="Savings or Checking Account"
ng-model="Account.acctType" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctType.$invalid && frmAccounts.acctType.$touched">Please indicate bank account type.</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Bank Account Current Balance </label>
<div class="col-sm-9">
<input type="text" class="form-control" id="acctBalance" name="acctBalance" placeholder="Enter current balance"
ng-model="Account.acctBalance" ng-required="true">
<span class="help-inline" ng-show="frmAccounts.acctBalance.$invalid && frmAccounts.acctBalance.$touched">Check Bank Account Balance</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btn-save" ng-disabled="frmAccounts.$invalid">Save Account</button>
</div>
</form>
</div>
</div>
<script included here, see below>
</body>
</html>
Then here is my AngularJS script (included in the body tag, below of my html page):
<script>
// Defining angularjs application.
var app = angular.module('addApp', []);
// Controller function and passing $http service and $scope var.
app.controller('addController', function($scope, $location, $http, $log, $window) {
var url = $location.absUrl();
$scope.url = $location.absUrl();
$http.get(url + "/api")
.then(function (response) {$scope.Account = response.data;}); //this part is working
$scope.submitForm = function(id) {
// Posting data to php file
$http({
method : 'POST',
url : 'https://mycrudapp-kkoyao.c9users.io/api/accounts/' + id,
data : $scope.Account,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('This is embarrassing. An error has occured. Please check the log for details');
});
});
</script>
The GET Method at the beginning is working fine and the data is fetched and displayed on the forms.
But when I click the "Save" Button to call the submitForm() function in my script, nothing happens and I get the error (see above) on my browser console (Chrome). But this script was edited and came from my CREATE a new entry feature, and was working fine. So I'm not sure what is the problem.
Anyway, here are my Laravel codes:
Laravel Route:
Route::post('/api/accounts/{id}', 'AccountCtrl#update');
Laravel Controller:
public function update(Request $request, $id) {
$account = Account::find($id);
$account->acctName = $request->input('acctName');
$account->acctNum = $request->input('acctNum');
$account->acctType = $request->input('acctType');
$account->acctBalance = $request->input('acctBalance');
$account->save();
}
I think the problem is in my Laravel controller, but not really sure how to fix it.
Also, how do I fix the code for DELETING data?
I'm sorry for this long, messy post, but it is my first time here and I really need help on this. Thank you very much.
Try to add to your web service the next header:
header("Access-Control-Allow-Origin", "*")
This is a CORS problem, probably because your browser is sending a preflight(OPTIONS) request. A quick search: https://github.com/barryvdh/laravel-cors
Edit: The OPTIONS request should return a 200 OK
I'm building a small web app (blog post alike) using AngularJs and Firebase. i implemented the addPost controller earlier and it worked good. After i wanted to add an input file inside the form which already implemented to upload images to firebase on form submit using ng-file-upload directive . As a new in angular i knew that firebase can save images as base64 but i couldn't figur out how to make it work.
Maybe some will say that its repeated question, but believe me i searched allover here i couldent find answer.
Here is my form file :
<div class="container" ng-controller="AddPostCtrl">
<form class="form-horizontal" ng-submit="AddPost(files)">
<fieldset>
<!-- Form Name -->
<legend>Create Post</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="txtTitle">Title</label>
<div class="col-md-4">
<input id="txtTitle" name="txtTitle" ng-model="article.title" type="text" placeholder="placeholder" class="form-control input-md">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost"></textarea>
</div>
</div>
<!-- Images -->
<div class="form-group">
<label class="col-md-4 control-label" for="pictures">Add Pictures</label>
<div class="col-md-4">
<input id="pictures" type="file" ngf-select ng-model="files" name="file"
accept="image/*" ngf-max-size="2MB" ngf-multiple="true" ngf-keep="true" ngf-keep-distinct="true" class="btn btn-primary"/>
<!-- Show image thumb and remove option -->
<span ng-repeat="file in files">
<img ngf-thumbnail="!file.$error && file" class="thumb"> <button class="btn btn-danger" ng-click="file = null" ng-show="file">Remove</button>
</span>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<input id="singlebutton" ng-disabled="!article.title || !article.post" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
</div>
</div>
</fieldset>
</form>
</div>
here is my controller :
angular.module('myApp.addPost', ['ngRoute'])
.controller('AddPostCtrl', ['$scope','CommonProp','$firebase','$location','Upload','$timeout', function($scope,CommonProp,$firebase,$location,Upload,$timeout) {
if(!CommonProp.getUser()){
$location.path('/main');
}
/***** Add data to firebase *****/
$scope.AddPost = function(files) {
var fb = new Firebase("https://hotelboard.firebaseio.com/Articles/");
var title = $scope.article.title;
var post = $scope.article.post;
var user = CommonProp.getUser();
var images = Upload.base64DataUrl(files).then(function(base64Urls){
fb.push({
title: title,
post: post,
emailId: user,
images : base64Urls,
'.priority': user
},function(error) {
if (error) {
console.log("Error:",error);
} else {
console.log("Post set successfully!");
console.log(images);
$location.path('/home');
$scope.$apply();
}
});
});
}
}]);
and here is my GitHub for full project files
https://github.com/SaidThaher/HotelApp
If i get help with this issue , it will be more question regards to the result.
PLEASE HELP
Update :
#danialfarid updated the directive and made my day :)
Upgrade to 8.0.6 and move your fb push here:
Upload.base64DataUrl(files).then(function(base64Urls) {
fb.push({...
images : base64Urls,
},...
});
I updated the code too.
Move your fb push here:
Upload.base64DataUrl(files).then(function(base64Urls) {
fb.push({...
images : base64Urls,
},...
});
Upload.base64DataUrl will convert the files to base64 data url which then can be added to the json to be sent to the server.
I have a form within my angular app (within SharePoint) that uses routing via hashbang, but when I click on a button in my form, it redirects to the root (like it can't resolve the URL so it uses the otherwise setting in my config), instead of executing the function.
Here is the HTML (my controller is defined in the routing):
<form name="newItem" class="form-horizontal" data-ng-submit="createItem()">
<fieldset>
<div class="form-group">
<label class="col-lg-2 control-label" for="itemtype">Type *</label>
<div class="col-lg-10">
<select class="form-control" id="itemtype" data-ng-model="selectedType"
data-ng-options="opt as opt.label for opt in types" required>
<option style="display:none" value="">Select a type</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="title">Title *</label>
<div class="col-lg-10">
<input class="form-control" name="title" id="title" type="text" data-ng-model="itemtitle" placeholder="Add your title (Limited to 70 characters)" data-ng-maxlength="70" required>
({{70 - newItem.title.$viewValue.length}} Characters Remaining)
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="body">Body *</label>
<div class="col-lg-10">
<textarea class="form-control" name="body" id="body" data-ng-model="itembody" rows="4" placeholder="Add your body (Limited to 500 characters)" data-ng-maxlength="500" required> </textarea>
Your summary will be displayed as follows ({{500 - newItem.body.$viewValue.length}} Characters Remaining):<br /> {{itembody}}
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" data-ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" data-ng-click="newItem">Submit</button>
</div>
</div>
</fieldset>
</form>
Here is my controller:
appControllers.controller('appItemPostCtrl', ['$scope', '$location', 'appItems', 'appTypes', function ($scope, $location, appItems, appTypes) {
var itemEntry = new appItems;
console.log(itemEntry);
$scope.types = [];
appTypes.query(function (typedata) {
var itemTypes = typedata.value;
// Foreach type, push values into types array
angular.forEach(itemTypes, function (typevalue, typekey) {
$scope.types.push({
label: typevalue.Title,
value: typevalue.Title,
});
})
});
$scope.createItem = function () {
itemEntry.Title = $scope.itemtitle;
itemEntry.$save();
}
$scope.cancel = function () {
}
}]);
UPDATE: It appears that this is related to SharePoint (My Angular Form is in SharePoint), as even setting the button type to submit as follows triggers the refresh instead of running the function. SharePoint is wrapping everything in a form since it inherits from the Master page of the Web, so when I added two "Angular Forms" to the page, the first angular form was closing the tag on the SharePoint form so the second was able to work. Does anyone have a stable workaround (beyond creating a custom masterpage). Image as follows:
I solved it by closing the tag of SharePoint instead of creating a custom masterpage. Ex:
<!-- Close the default form tag put in place by SharePoint instead of creating a custom Masterpage without this element that requires increased permissions and complexity to deploy. Without this tag closed, the form below will not render properly -->
</form>
<div>
<form id="newItemForm" class="form-horizontal" data-ng-submit="createItem()">
<div class="form-group">
<label class="col-lg-2 control-label" for="itemtype">Type *</label>
<div class="col-lg-10">
<select class="form-control" id="itemtype" data-ng-model="selectedType"
data-ng-options="opt as opt.label for opt in types" required>
<option style="display:none" value="">Select a type</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="title">Title *</label>
<div class="col-lg-10">
<input class="form-control" name="title" id="title" type="text" data-ng-model="itemtitle" placeholder="Add your title (Limited to 70 characters)" data-ng-maxlength="70" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="body">Body *</label>
<div class="col-lg-10">
<textarea class="form-control" name="body" id="body" data-ng-model="itembody" rows="4" placeholder="Add your body (Limited to 500 characters)" data-ng-maxlength="500" required> </textarea>
</div>
</div>
<div class="col-lg-10 col-lg-offset-2">
<!--<button type="button" class="btn btn-default" data-ng-click="cancel()">Cancel</button>-->
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
Add type='button' to the buttons. I had this same problem before and assumed it was an angular bug of some kind.
Do both buttons exhibit this behavior or just the Submit button?
The submit button calls newItem from ng-click, but the name of the function in the js is actually createItem.
I use angular-bootstrap and and Angular Smart table.
I have a modal form which adds new records to database and shows the list in my smart table. Adding new records is working fine but how do I refresh my smart table after a new record is inserted into the database.
Controller
//ajax request to gather data and list in smart table
october.controllers['dashboard/feeds'] = function ($scope, $filter , $request, $modal, $log, $http) {
$scope.api = $request('onFeeds', {success: function(data, scope){
this.success(data).done(function() {
$scope.rowCollection = [];
$scope.rowCollection = angular.fromJson(data.result);
$scope.displayedCollection = [].concat($scope.rowCollection);
});
}
});
}
//Modal
var ModalInstanceCtrl = function ($scope, $modalInstance, $request, $filter) {
$scope.save = function (data) {
$request('onAddFeed',
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
});
};
};
Template
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">neue Feed eintragen!</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<input type=hidden ng-init="formInfo.user_id = {% endverbatim %} {{ user.id }} ">
{%verbatim %}
<div class="form-group">
<label for="inputName3" class="col-sm-2 control-label">Feed Name</label>
<div class="col-sm-8">
<input class="form-control" id="inputName3" placeholder="Feed Name" ng-model="formInfo.name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Feed Type</label>
<div class="col-sm-8">
<select ng-model="formInfo.feed_type" class="form-control">
<option>Select Feed Source</option>
<option value="api">API</option>
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
<option value="upload">Upload</option>
</select>
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='api'">
<label for="selectAPI" class="col-sm-2 control-label">Select API</label>
<div class="col-sm-8">
<select ng-change="selectAction(item.id)" ng-model="formInfo.network_id" ng-options="item.id as item.name for item in networks" class="form-control"> </select>
</div>
</div>
<div class="form-group" ng-repeat="setup in setups">
<label for="setup" class="col-sm-2 control-label">{{setup}}</label>
<div class="col-sm-8">
<input ng-model="formInfo['api_credentials'][setup]" class="form-control" placeholder="Enter your {{setup}}">
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='xml' || formInfo.feed_type =='csv' ">
<label for="inputPassword3" class="col-sm-2 control-label">Source</label>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-link"></i></div>
<input ng-model="formInfo.source" type="text" class="form-control" id="sourceInput" placeholder="URL">
</div>
</div>
</div>
</div>
<span>{{formInfo}}</span>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-click="save(formInfo)">Save</button>
<button type="button" class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
In the above code Instead of $scope.refresh() use $route.reload() to
Update the records before closing Modal Instance.
reload() Causes $route service to reload the current route even if $location hasn't changed
To refresh the smart-table you can add or remove items or just recreate the array.
$scope.tableData = [].concat($scope.tableData);
The thing that worked for me (and appears to be causing you the problem) is to set displayedCollection to an empty array. Smart Table will fill it with whatever paged, filtered, or sorted data you designate. Something like this:
<table st-table="displayedCollection" st-safe-src="rowCollection">
All of a sudden, rowCollection.push(data) automatically updated the Smart Table.