How to add value to ng-model in Angularjs - javascript

How to add value to ng-model in angularjs. my html is:
<textarea rows="5" ng-model="comment.comment_text"></textarea>
<input type="hidden" ng-model="comment.task_id" value="{{task.id}}">
<input type="hidden" ng-model="comment.user_id" value="{{profile.id}}">
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>
and angular controller:
$scope.create = function(comment) {
console.log(comment);
};
when click on button show result in console:
{comment_text: "test"}
BUT I want to show like this:
{comment_text: "test", user_id:1 ,task_id:53}

On your controller's constructor you should definitely instantiate the initial value of your 'comment' variable using:
$scope.comment = $scope.comment || {
user_id: 'amcpanaligan',
comment_text: 'sample'
//// other object property declaration goes here...
};

value={{someValue}} does not make sense.
You should use only ng-model for text input hidden
function Ctrl($scope) {
$scope.task = {
id: 1
}
$scope.create = function(comment) {
comment.taskId = $scope.task.id;
console.log(comment);
};
}
<div ng-app="">
<div ng-controller="Ctrl">
<textarea rows="5" ng-model="comment.comment_text"></textarea>
<input type="hidden" ng-model="task.id">
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>
</div>
</div>
see fiddle

Related

ng-view scope communicating with main scope communication

It's maybe a stupid question but it's late and i'm desperate.
I have a angularjs application that uses ngRoute. But everything is done in one controller. Now I have a form in a view and the use of that form is to put it's input field data into a var to send with post.
Don't mind al the console log i'm trying to find the error.
APP.JS
`
$scope.addDevice = function(){
$scope.device = {};
var data = {
'Name' : $scope.device.ChildName,
'Serial' : $scope.device.Serial
};
console.log($scope.device.Serial);
console.log($scope.device.ChildName);
console.log(data);
$http.post('http://141.135.5.117:3500/device/register', data, { headers: headers })
.then(function(response){
console.log(response);
console.log(headers);
});
}`
Settings.html ( Note: this is a view in ng-view)
<form role="form" class='userForm'>
<label for="addDevice">Add Device</label>
<input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="$scope.device.Serial">
<input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="$scope.device.ChildName">
<button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
<p>{{$scope.device.Serial}}</p>
</form>
This is the console output
Console output
All the functions are done in one controller.
First Remove $scope from ng-model="$scope.device.Serial"
and define $scope.device = {}; outside $scope.addDevice = function(){
$scope.device = {};
$scope.addDevice = function(){
-- you code here --
}
Working code example
angular.module('inputExample', [])
.controller('ExampleController', ['$scope','$http', function($scope,$http) {
$scope.val = '1';
$scope.device = {};
$scope.addDevice = function(){
var data = {
'Name' : $scope.device.ChildName,
'Serial' : $scope.device.Serial
};
console.log($scope.device.Serial);
console.log($scope.device.ChildName);
console.log(data);
$http.post('http://141.135.5.117:3500/device/register', data)
.then(function(response){
console.log(response);
console.log(headers);
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="inputExample">
<div ng-controller="ExampleController">
<form role="form" class='userForm'>
<label for="addDevice">Add Device</label>
<input type="text" class="form-control" id="deviceserial" placeholder="Enter serial number" ng-model="device.Serial">
<input type="text" class="form-control" id="Devicechildname" placeholder="Enter baby name" ng-model="device.ChildName">
<button type="submit" class="btn btn-success btn-block" ng-click="addDevice()">Add Device</button>
<p>{{device.Serial}}</p>
</form>
</div>
</div>

Angular -multi step form

How I can set val1 to $_POST variable ? Because in step 2 val1 is null.
I try to use $scope, $rootScope, angular.copy() and .val().
This is my html code:
<html ng-app="myApp"><body>
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="val1">
<button type="button" ng-click="vmForm.stepTwo()"></button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</body>
JS
<script>
angular.module('myApp', ['ngAnimate'])
.controller('FormController', FormController);
function FormController($scope) {
var vm = this;
vm.step = "one";
vm.stepTwo = stepTwo;
function stepTwo() {
vm.step = "two";
}
}</script>
$_POST is a PHP variable that's accessible on the server. It contains the payload or request body that's sent in a HTTP POST request as an associative array. It cannot be set directly using Javascript / AngularJS.
What you can do is construct your request data and make a $http POST request to your form action endpoint. Here's a working example based on the code you posted: http://plnkr.co/edit/C1FGvoDrmzYEFMCwymIG?p=preview
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>Hello Plunker!</h1>
<form ng-submit="formSubmit()" ng-controller="FormController">
<p>Val1: {{val1}}</p>
<p>Val2: {{val2}}</p>
<div ng-switch="vm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="$parent.val1">
<button type="button" ng-click="stepTwo()">Go to Step two</button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="$parent.val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('FormController', ['$scope','$http',function ($scope,$http) {
$scope.vm = {
step : "one"
};
$scope.val1 = "";
$scope.val2 = "";
$scope.stepTwo = function () {
$scope.vm.step = "two";
}
$scope.formSubmit = function () {
console.log($scope.val1, $scope.val2);
var req = {
url : 'url.php',
method: 'POST',
data : {
val1 : $scope.val1,
val2 : $scope.val2
}
};
$http(req).then(function(response) {
console.log('success', response);
}, function(errorResponse){
console.log('error', errorResponse);
});
}
}]);
Just leave everything as is in your controller and tweak your HTML like this:
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="vmForm.val1">
<button type="button" ng-click="vmForm.stepTwo()">Goto Step 2</button>
</div>
<div class="steptwo" ng-switch-when="two">
<input type="hidden" name="val1" value="{{vmForm.val1}}">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
The tweak to your code is simply raising the scope of "val1" to "vmForm.val1" so in Step 2 "vmForm.val1" can be assigned to a hidden input field for posting.
Here's the form fields being posted in the browsers debugger:
Here's a Plunker, http://plnkr.co/edit/3VaFMjZuH09A4dIr1afg?p=preview
Open your browsers debugger and view network traffic to see form fields being posted.

Angular $setPristine is not working

Html :
I'm using controller as syntax.
<form name="occupantDetailForm" role="form" novalidate class="form-validation">
<div class="form-group form-md-line-input form-md-floating-label no-hint">
<input class="form-control" type="text" name="LastName" ng-model="vm.occupantDetail.lastName" ng-class="{'edited':vm.occupantDetail.lastName}" maxlength="#OccupantDetail.MaxLength" required>
<label>#L("LastName")</label>
</div>
<button type="submit" class="btn btn-primary blue" ng-click="vm.saveOccupantDetail(occupantDetailForm)" ng-disabled="occupantDetailForm.$invalid"><i class="fa fa-save"></i> <span>#L("Save")</span></button>
</form>
JS :
vm.saveOccupantDetail = function (form) {
vm.occupantDetailForm = form;
createOrEditOccupantDetail();//create or edit
vm.occupantDetail = {};
vm.occupantDetailForm.$setPristine();
}
Q : I have tried many ways but it is not working ? When I use the vm.occupantDetailForm.$setUntouched(); then it works fine.But then the problem is Save button is not being disabled.Could you tell me why ? When I use the vm.occupantDetailForm.$setPristine(); only then it is not working at all.Why ? Thanks.
$setPristine only marks your form as $pristine and to actually reset the form you need, set your model to a new object.
A better explanation is given here in the link:
$setPristine not working
Below is some code which might help you:
<div ng-app="myapp">
<div ng-controller="UserCtrl">
<form name="user_form" novalidate>
<input name="name" ng-model="user.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>
Pristine: {{user_form.$pristine}}
</p>
</div>
</div>
Controller Code:
var app = angular.module('myapp', []);
function UserCtrl($scope) {
$scope.reset = function() {
$scope.user = {};
$scope.user.name = "";
$scope.user_form.$setPristine();
$scope.user = {};
}
}
A fiddle:
http://jsfiddle.net/p7e1nway/1/
Update:, can you try setting $submitted to false
$scope.occupantDetailForm.$setPristine();
$scope.occupantDetailForm.$setUntouched();
$scope.occupantDetailForm.$submitted = false;

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

add and delete json list inside ng-repeat

i want to create a page where someone adds 1 or more locations to a contact and right now i have something that looks like this.
<div class="input-append" ng-repeat="location in newPartner.partner_location">
<input class="input-large" type="text" ng-model="location">
<button class="btn" type="button" ng-click="delLocation1({{$index}})">- {{$index}}</button>
</div>
<div class="input-append">
<input class="input-large" type="text" ng-model="new_location">
<button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>
This is the HTML and the controller looks like this.
$scope.newPartner = {'partner_name':'newname','partner_location':['X','Y','Z']};
$scope.addLocation1 = function() {
$scope.newPartner.partner_location.push($scope.new_location);
$scope.new_location = "";
}
$scope.delLocation1 = function(id) {
$scope.newPartner.partner_location.splice(id, 1);
}
Now it works great on begin but if i delete some items and add some it suddenly bugs out and starts to delete the previous item instead the one i press - (minus) on.
Is there something i did wrong? Thank you in advance, Daniel!
First off remove {{}} from ng-click="delLocation1({{$index}})". It should be:
ng-click="delLocation1($index).
Second, I suggest you to add some basic debugger to see what happens with our model when we add new value: <pre>{{newPartner.partner_location|json}}</pre>
Third, I would change the model to:
$scope.newPartner = {
'partner_name': 'newname',
'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
};
because, by this way: ['X','Y','Z'] we can't modify our data.
Demo Fiddle
Finally this is our fixed code:
HTML
<div ng-controller="fessCntrl">
<div ng-repeat="location in newPartner.partner_location">
<input class="input-large" type="text" ng-model="location.value">
<button class="btn" type="button" ng-click="delLocation1(newPartner.partner_location, $index)">{{$index}}</button>
</div>
<div class="input-append">
<input class="input-large" type="text" ng-model="new_location">
<button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>
<pre>{{newPartner.partner_location|json}}</pre>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.new_location = "empty";
$scope.newPartner = {
'partner_name': 'newname',
'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
};
$scope.addLocation1 = function () {
$scope.newPartner.partner_location.push({value:$scope.new_location});
$scope.new_location = "empty";
}
$scope.delLocation1 = function (locations, index) {
locations.splice(index, 1);
}
});
fessmodule.$inject = ['$scope'];

Categories

Resources