How to load form with values based on Angular $resource - javascript

I want CRUD operations so that when a user clicks on any particular item to edit this form will be filled with those values (that the user wants to edit).
Here is my code .
storeView.html
<tr data-ng-repeat="store in stores | filter:search | orderBy:'name'">
<td>
{{ store.name }}
</td>
<td class="icons-width">
<a href="#/Store/edit/{{store._id}}" id="edit" data-toggle="tooltip">
<i class="fa fa-pencil fa-fw colorInfo" ></i>
</a>
<a ng-click="deleteStore(store._id)" id="delete" data-toggle="tooltip">
<i class="icon-trash"></i>
</a>
</td>
</tr>
So when a user clicks on edit for a particular store it will go to another view which has the a form that will show which values the user wants to edit.
storeformView.html
form class="form-horizontal" name="store_form" novalidate ng-submit='AddStore()'>
<div class="modal-header">
<h3>Create/Edit Store</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="store_Name" class="col-lg-4 form-label">Name:</label>
<div class="col-lg-7">
<input type="text" class="form-control" ng-model="store.name" id="store_Name" name="store_Name" placeholder="Store Name" required/>
<div class="error" ng-show="store_form.store_Name.$dirty && store_form.store_Name.$invalid">
<small class="error errorFields" ng-show="store_form.store_Name.$error.required">
Store Name is required.
</small>
</div>
</div>
</div>
<div class="form-group">
<label for="store_AddressLine1" class="col-lg-4 form-label">Address Line 1:</label>
<div class="col-lg-7">
<input type="text" class="form-control" ng-model="store.address1" id="store_AddressLine1" name="store_AddressLine1" placeholder="Address Line 1" required/>
<div class="error" ng-show="store_form.store_AddressLine1.$dirty && store_form.store_AddressLine1.$invalid">
<small class="error errorFields" ng-show="store_form.store_AddressLine1.$error.required">
Address is required.
</small>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="store_form.$invalid">
<i class="icon-ok-sign icon-white"></i> Save
</button>
<a class="btn btn-default" href="#/Stores">
<i class="icon-remove-circle" ></i>
Cancel
</a>
</div>
</form>
storeFactory.js
app.factory('Store', function ($resource) {
return {
getAllStores : $resource("/store/list" ,{},{ TypeGetStores:{method: 'get', isArray:true}}),
getStore : $resource("/store/:id" ,{id : #id},{ TypeGetStore:{method: 'get'}}),
};
});
app.js
var app = angular.module('myApp', ['ngCookies','ngResource', 'ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/Stores',
{
templateUrl: '/app/partials/StoresListView.html'
})
.when('/Store/edit/:storeId',
{
templateUrl: '/app/partials/StoreFormView.html'
})
.otherwise({ redirectTo: '/Login' });
});

For loading information about your store, you can use resolve parameter in routeProvider :
.when('/Store/edit/:storeId',
{
templateUrl: '/app/partials/StoresListView.html',
resolve: {app: function($scope,Store,$routeParams) {
$scope.store = Store.getStore({id:$routeParams.id})
}
}
If everything is right and that's how your factory will work (if that function really returns store. Maybe it returns JSON with root, then you should specify, how to get store from that JSON), than you will have $scope.store in your controller, and it will be two-way-binded with what you have in form.
Note: page will load only after resolve is fully done.

Related

Checkboxes weird behaviour in AngularJS ng-repeat

I've a form containing input fields and checkboxes (table crud generating dynamically). See the image below:
Here, In my clients modal dialog form I've implemented small crud for adding/updating/deleting Providers data and showing table below of it on the fly.
Following is my code:
View:
<form name="clientForm" ng-submit="check(id)" ng-controller="ClientsController">
<div class="form-group">
<label for="name">Name</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Name" ng-model="client.name">
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Email" ng-model="client.email">
</div>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Phone" ng-model="client.phone">
</div>
</div>
<div class="form-group">
<label for="phone">Providers</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" ng-model="provider.provider_name" placeholder="Enter Provider Name">
</div>
<br>
<button type="button" id="addbtn" class="btn btn-sm btn-primary" ng-click="addProvider()">Add Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-info" ng-click="updateProvider(id)">Update Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-default" ng-click="clearProvider()">Clear Provider</button>
<br>
<table style="width: 50%; margin-top: 10px;" class="">
<tbody>
<tr ng-repeat="val in providersData">
<td>
<input type="checkbox" name="providersData" ng-model="$parent.client.providersList" value="{{val._id}}"/>
</td>
<td>{{val.provider_name}}</td>
<td>
<a style="color: blue;" href="javascript:void(0);" ng-click="editProvider(val._id)"><i class="glyphicon glyphicon-edit"></i></a>
<a style="color: red;" href="javascript:void(0);" title="Delete" confirmed-click="removeProvider(val._id)" ng-confirm-click="Are you sure you want to remove provider?"><i class="glyphicon glyphicon-trash"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="well well-lg text-center bg-gray">
<button class="btn btn-success" ng-if="id">Save Client</button>
<button class="btn btn-danger" ng-if="id" title="Delete" confirmed-click="remove(client._id)" ng-confirm-click="Are you sure you want to remove?">Delete</button>
<button type="button" class="btn btn-warning" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button class="btn btn-success" ng-if="!id">Add Client</button>
</div>
</form>
Controller:
$scope.showModal = false;
$scope.client = {};
$scope.provider = null;
$scope.addClient = function () {
alert(JSON.stringify($scope.client));
$http.post('/clients', {param: $scope.client}).success(function (response) {
if (response) {
alert("Client added successfully");
$scope.client = "";
refresh();
$scope.closemodal();
}
});
};
Now I want to insert/update selected checkboxes value to db along with Name, Email, and Phone field.
Here I'm facing following issues:
Whenever I'm clicking on any checkbox its checking all checkboxes.
After clicking on Add Client button its showing result of alert(JSON.stringify($scope.client)) like this
{"name":"asdfdsafasdf","email":"sdf","phone":"sadf","providersList":{"id":true}}
In mongodb its showing like this:
I've search a lot tried this and ng-model="$parent.client.providersList.id" but still its not working.
I'm beginner in AngularJS and just started working on it.
Any help would be appreciated.
You should use ng-true-value & ng-false-value over the checkbox(I'm considering default value to be 0). And then use $index of providersData ng-repeat to create an array of client.providersList.
Markup
<input type="checkbox" name="{{'providersData'+$index}}"
ng-model="client.providersList[$index].id" ng-true-value="val._id" ng-false-value="0" />
You are facing this problem because of the value of your ng-model attribute. The value for ng-model attribute must be different for each checkbox. Here, try this:
<input type="checkbox" name="providersData" ng-model="client.providersList{{$index}}" ng-value="val._id" />
Try something like this:
$scope.client = {};
$scope.client.providersList = [];
// Now watch the model for changes
$scope.$watch('client', function(){
// When the checkbox is selected it returns true
if($scope.client.providersList1 == true){
$scope.client.providersList.push({"id": value})
}
// Repeat the if statements for all the checkboxes (or use a for loop)
}, true);

How to get input from user display in HTML page

I encounter a problem to display input from user into this table.
<tr ng-repeat="user in users" ng-class-even="'bg-light-grey'" ng-if="isLoading==false">
<td>
<div> {{user.username}} </div>
</td>
<td>
<div> {{user.name}} </div>
</td>
</tr>
If user click this "edit user" button, the form will appear.
<div class="glyphicon glyphicon-lock" ng-click="editUser();">
This is form that require user to fill edit their username and name
<div class="dialog-contents">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Edit User</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form name="edituser">
<div class="form-group has-feedback" ng-class="editUser.username.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Username">Username</label>
<div class="col-sm-10">
<input type="username" ng-model="user.username" class="form-control" id="Username" placeholder="Enter Username"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.username.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
<div class="form-group has-feedback" ng-class="editUser.name.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Name">Name</label>
<div class="col-sm-10">
<input type="name" ng-model="user.name" class="form-control" id="name" placeholder="Enter Name"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.name.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
Form this form, if user click this "submit" button, the user details will appear in table as i provide the code above.
<button type="submit" class="btn btn-primary" ng-click="add();"
ng-class="isLoading ? 'disabled' : '';">Submit </button>
Now, i want to push the input from user, and display it in the table. But i am stuck in developing the controller to get the input and displayed it. Appreciate if someone can help solve this problem.
app.register('user', ['$scope', 'ngDialog', function ($scope, $dialog) {
$scope.isLoading = false;
$scope.addUser = function(){
$dialog.open({
showClose: false,
closeByEscape: true,
template: 'view/user/user-user-add.html',
controller: ['$scope', function ($dialogScope) {
$dialogScope.users = {
username : "" ,
name : "",
status : "",
}
.closePromise.then(function (data)
$dialogScope.hasError = false;
$dialogScope.errorMessage = '';
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
}
}]
});
};
}]);
In your add function, close the dialog and pass the new user object to close promise, like this: -
//your dialog controller
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
};
you main controller: -
$scope.addUser = function(){
$dialog.open({
....
})
.closePromise.then(function (data) {
console.log(data);
//check and find user from the data and do what you need, i.e. $scope.users.push(user);
});
};

How to return the value of textbox using Ionic?

I have a form in Ionic and I am trying to return the value of the textbox, but am having issues. The rest of the form is loading and 'signup' is returned to the console. formData.email isn't bound in the template and neither is anything returned to the console when I type something in and click the button.
Any advice on what to do?
signup.html
<!-- Header -->
<div class="bar bar-header bar-light">
<button class="button icon-left ion-chevron-left button-clear button-dark">Back</button>
<h1 class="title">Signup</h1>
</div>
<!-- Space between header and signup form -->
<div class="spacer" style="width: 300px; height: 50px;"></div>
<div class="list list-inset">
<!-- Signup form text fields -->
<form>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="email" ng-model="formData.email">
</label>
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password">
</label>
<!-- Submit button for signup form -->
<button on-touch="onTouch()" class="button button-positive button-block">
Sign up
</button>
</form>
</div>
{{formData.email}}
controllers.js
.controller('SignupCtrl', function($scope, $ionicLoading, $state, $stateParams){
console.log('signup');
$scope.formData = {};
//Go to the guessing page
$scope.onTouch = function(item,event){
console.log($scope.formData.email);
};
});
What you're doing is correct, the only thing that I could do to recreate this was if you haven't entered a valid email address it returns undefined. This is a validation feature built in to Angular itself and has nothing to do with Ionic. You can find out more about this here: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

Angularjs ui tabset scope not updating

I am using tabs from angular ui bootstrap.
All works fine but I noticed that text boxes inside the tab is not updating the scope although using ng-model.
I searched and found out that it is because of child scope and advise of using obj.property notation while binding.
but still my model is not being updated.
Please guide where I am going wrong.
wbProcess.controller ("createProCtrl", function ($scope, $http, global, user){
$scope.project = [{protitle :""},
{prodesc : ""},
{chkarchive : false}
];
$scope.tab = true;
$scope.upurl;
$scope.createpro = function(){
$http({
url: global.apiurl+"pro/create",
method: "POST",
data: {'name': $scope.project.protitle, 'prodesc': $scope.project.prodesc, 'owner': user.user_id , 'active': $scope.project.chkarchive}
}).success(function (data, status, headers, config) {
// assign $scope.persons here as promise is resolved here
//$log.log(data);
if(data.status > 0){
$scope.tab = false;
}
else{
}
}).error(function (data, status, headers, config) {
$scope.status = status;
$log.log(status);
});
}
});
HTML is
<tabset>
<tab>
<tab-heading>
<i class="green icon-edit bigger-110"></i>Description
</tab-heading>
<div>
<form name="createProForm" class="form-horizontal">
<div class="control-group span7">
<label class="control-label" for="form-field-1">Title</label>
<STYLE type="text/css">
.ng-dirty.ng-valid ~ span.ok { color:green; display:inline; }
.ng-dirty.ng-invalid ~ span.ko { color:red; display:inline; }
</STYLE>
<div class="controls">
<input type="text" name="protitle" id="projecttitle" ng-model="project.protitle" ng-unique="projects" placeholder="Title" required />
<span class="red" ng-show="createProForm.protitle.$error.unique" >
<i class="red icon-asterisk bigger-110"></i> Project Title already exists.</span>
<!--<span class="green" ng-show="createProForm.protitle.$error.unique === false" >
<i class="green icon-asterisk bigger-110"></i> Available</span>
-->
</div>
</div>
<div class="control-group span5">
<div class="controls">
<input class="ace" type="checkbox" id="id-disable-check" ng-model="project.chkarchive" tabindex="-1"/>
<label class="lbl" for="id-disable-check"> Archive Project</label>
</div>
</div>
<div class="control-group">
<label class="control-label" for="form-field-9">Project Description</label>
<div class="controls">
<textarea class="span7" id="projecttitle" ng-model="project.prodesc" maxlength="100" placeholder="100 Character Limit" required></textarea>
</div>
</div>
<div class="form-actions">
<button class="btn btn-info" type="button" ng-disabled="createProForm.protitle.$pristine || createProForm.protitle.$dirty && createProForm.protitle.$error.unique === true" ng-click="createpro()">
<i class="icon-ok bigger-110"></i>
Save
</button>
<button class="btn" type="reset">
<i class="icon-undo bigger-110"></i>
Reset
</button>
<button class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable / Disable third tab</button>
</div>
</form>
</div>
</tab>
<tab disabled = "tab">
<tab-heading>
<i class="green icon-cogs bigger-110"></i>Configuration
</tab-heading>
<div>
<div class="span6">
hi
</div>
<div id="dropzone" class="span6">
<input type="hidden" id="upurl" value="{{ upurl }}" />
<form action="/not-found" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</form>
</div>
</div>
</tab>
<tab disabled = "tab">
<tab-heading>
<i class="green icon-group bigger-110"></i>Users
</tab-heading>
<div>
<p>Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade.</p>
</div>
</tab>
The text input is only in first tab.
There is one solution to access it.
You can access it using the following syntax in your controller.
$scope.$$childHead.$$nextSibling.yourVariablename.
For example you have ng-model="state" on html page you can access it like this
$scope.$$childHead.$$nextSibling.state
The advise of using obj.property notation while binding because of child scope is correct, but you wrongly defined $scope.project as a list of objects instead of just a simple object with multiple key/value pairs.
Try:
$scope.project = {
protitle: "",
prodesc : "",
chkarchive: false
};
See also here

$scope unidefined in modal angular js

i am using modal in angular but when modal open so here values are not binding with model i don't know why this happening must be appreciates if some corrected if there is any mistake thanx.
modal.html
<script type="text/ng-template" id="categoryModal.html">
<form class="form-horizontal" name="category_form" novalidate>
<div class="modal-header">
<a class="close" ng-click='cancel()'><i class="icon-remove-circle icon-bold"></i> </a>
<h3>Category</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="category_Name" class="col-lg-3 form-label">Category Name:</label>
<div class="col-lg-8">
<input class="form-control" id="category_Name" ng-model="category.name" name="category_Name" placeholder="Category Name" required/>
<div class="error" ng-show="category_form.category_Name.$dirty && category_form.category_Name.$invalid">
<small class="error errorFields" ng-show="category_form.category_Name.$error.required">
Category Name is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button ng-click='saveCategory()' class="btn btn-primary" ng-disabled="category_form.$invalid">
<i class="icon-ok-sign icon-white"></i> Add
</button>
<button ng-click='cancel()' class="btn btn-warning">
<i class="icon-remove-circle icon-white"></i> Cancel
</button>
</div>
</form>
</script>
modalController.js
app.controller('brandModalCtrl', function ($rootScope, $scope, $modalInstance) {
// Save Brand
$scope.saveCategory = function () {
console.log($scope.category) // undefined
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
I would try adding the same $scope to modalOptions and letting the modal share the controller's $scope variables. Putting both onto $rootScope is too drastic. Ideally, your modal should have an isolate scope, but it sounds like you need some overlap.

Categories