ng-model data not getting when saving the data - angularjs

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...

I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Related

How to pass data-plugin="timepicker" value to controller in angularJS

I have code to pass date and time to controller.
Here is HTML code,
<div class="page-content" ng-app="app">
<div ng-controller="postAppoinmentCtr as ctrl" class="panel-body">
<form ng-submit="submitForm()" id="form1">
<input name="time" ng-model="time" type="text" class="form-control" ng-model="time" data-plugin="timepicker" autocomplete="off"/>
<input name="date" ng-model="date" type="text" class="form-control" data-plugin="datepicker"/>
<input..ng-model="type"...></input>
<input..ng-model="Description"...></input>
<button ...>
</form>
</div>
</div>
Here is angular js part
var app = angular.module('app', []);
app.controller('postAppoinmentCtr', function($scope, $http, $location) {
$scope.submitForm = function(){
var url = $location.absUrl() + "/addAppoinment";
alert(url);
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
var data = {
type: $scope.type,
date: $scope.date,
time: $scope.time,
description: $scope.description
};
$http.post(url, data, config).then(function (response) {
$scope.postResultMessage = "Sucessful!";
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.type = "";
$scope.date = "";
$scope.time ="";
$scope.description ="";
}
});
When click the button type and description pass to controller. But date and time not. I can do this using
<input id="date-birth" class="form-control" type="date" ng-model="date">
this line. But I need to use data-plugin="datepicker" .
I'm new one for the angularjs and I try to many ways for solve this problem.
Please give me some answer this. Thanks in advance.

AngularJS Textarea If data Is loading

I have a textarea that relies upon a dropdown menu to populate. When the dropdown is changed, a file is pulled and the contents are loaded to the textarea.
While the textarea is loading, it just says [object Object]. I'd like it to be a bit nicer than that. Something like 'Loading...'.
I cant find away to specifically do this with a textarea though.
Another wrench in the wheel is that the Save functionality actually relies upon the value of the text area to save, so I cant just alter the content of the text area to display 'Saving...' otherwise the content that is written to the file is just 'Saving...'.
Here is the code:
View
<div id="Options" class="panel-collapse collapse">
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon input-sm">Config Select</span>
<select ng-change="update()" ng-model="configFileName" class="form-control input-sm">
<option>--</option>
<option ng-repeat="conf in configList" value="{{conf.name}}">{{conf.name}}</option>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<td style="padding-bottom: .5em;" class="text-muted">Config File</td><br />
<textarea id="textareaEdit" rows="20" cols="46" ng-model="configFileContent"></textarea>
<input type="button" ng-click="updateConfig()" style="width: 90px;" value="Save"></button>
</div>
</div>
</div>
</div>
JS
$scope.update = (function(param) {
$scope.configFileContent = 'Loading...';
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'getConfigFileContent',
method: 'POST',
data: $scope.configFileName
}, function(response) {
$timeout(function() {
console.log('got it');
$scope.configFileContent = response.confFileContent;
}, 2000);
});
});
$scope.updateConfig = (function(param) {
var data = [$scope.configFileName, $scope.configFileContent];
var json = JSON.stringify(data);
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'saveConfigFileContent',
method: 'POST',
data: json
}, function(response) {
$timeout(function() {
console.log('Saved!');
$scope.update();
}, 2000);
});
});
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope, $timeout) {
$scope.update = function() {
if ($scope.selectedData === '') {
$scope.someData = '';
return;
}
// do http response
var data = 'dummy file text from server';
$scope.xhr = false;
$scope.msg = 'loading...';
// simulating fetch request
$timeout(function() {
$scope.xhr = true;
$scope.content = data;
}, 3000);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<select ng-model="selectedData" ng-change="update()">
<option selected="selected" value="">Select data</option>
<option value="foo">Fetch my data</option>
</select>
<br><br><br>
<textarea rows="5" cols="20" ng-model="someData" ng-value="xhr === false ? msg : content">
</textarea>
</div>
You can use a scope variable to detect the completion of promise request of xhr and simulate a loading... message.
As for save, i recommend not to use such approach of displaying message inside textarea and instead create another directive/component to detect the loading and saving request completion which is reusable and separates business logic keeping controller thin.

ng-show not watching variable change

I have a progress bar I want to show after I click a button.
I set my variable to true on click, yet it's not working.
The ng-show in question is on the bottom of the html, and the button i click is on a different html page but i didn't include because it uses the successOnClick function in this same controller. I console logged the isEmailing variable inside the onclick and it is assigned true. Doesn't work for ng-if either
What gives?
module.exports = app => {
app.controller('ContactController', ($scope, $http) => {
$scope.isEmailing = false;
$scope.email = (e) => {
$scope.isEmailing = true;
const requestBody = {};
const id = e.target.id;
requestBody.name = document.getElementById(`${id}-name`).value;
requestBody.email = document.getElementById(`${id}-email`).value;
requestBody.subject = document.getElementById(`${id}-subject`).value;
requestBody.body = document.getElementById(`${id}-body`).value;
$http.post('/email', JSON.stringify(requestBody), {
'Content-Type': 'application/json'
})
.then(res => {
console.log('Success!');
document.getElementById(`${id}-name`).value = '';
document.getElementById(`${id}-email`).value = '';
document.getElementById(`${id}-subject`).value = '';
document.getElementById(`${id}-body`).value = '';
$scope.isEmailing = false;
})
.catch(err => {
console.log('Error!');
$scope.isEmailing = false;
})
}
$scope.successOnClick = () => {
$scope.isEmailing = true;
}
})
}
<footer class="footer" ng-controller="ContactController">
<div class="footer__block social-media-container">
<div class="social-media">
<img src="http://i.imgur.com/bVqv5Kk.png" alt="fb-icon">
<img src="http://i.imgur.com/sJWiCHV.png" alt="twitter-icon">
<img src="http://i.imgur.com/o7yTVyL.png" alt="insta-icon">
</div>
</div>
<div class="footer__block">
<form class="footer__form" ng-submit="email($event)" id="footer">
<textarea placeholder="Message" id="footer-body" required></textarea>
<input type="text" placeholder="Name" id="footer-name" required>
<input type="email" placeholder="Email" id="footer-email" required>
<input type="text" placeholder="Subject" id="footer-subject" required>
<input type="submit" placeholder="Email">
</form>
</div>
<div class="footer__block mailing-list">
<span>Join our Mailing List!</span>
<form>
<input type="email" placeholder="Email" required>
<input type="submit">
</form>
</div>
<!-- <div class="grey-screen">
<div class="success">
<h1>Success!</h1>
</div>
</div> -->
<div class="progress-bar" ng-show="isEmailing">
</div>
</footer>
If you have several controller of same type it is not mean, that they all are same the instance. AngularJS creates controllers not via singleton pattern. You should synchronize them by yourself by means of events:
angular.module('app', [])
.controller('MyController', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.$on('Changed', function(event, data){
$scope.isEmailing = data;
})
$scope.successOnClick = function(){
$scope.$emit('Changed', !$scope.isEmailing);
}
}]);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">First controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">Second controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
</div>
If one controller located inside another you can try to use $scope.$parent.isEmailing(where .$parent can be typed several times, depending on nesting level), but it is very uncomfortable. If your controllers located at different routes, you should pass data from one controler to another via route parameters or custom AngularJS service or $rootScope.

Get data from controller in Angular js

I tried to create a small service for adding and getting. I have successfully added details when I click register(form details are added)in one controller. Now I want that form details in another controller, but I'm not getting it. I'm able to get that details in that get function and able to print in console but I cannot pass them to html
Here is my HTML:
<div id="inputArea" style="border: 1px solid blue;width: 800px;height: 45px;margin: auto;" ng-controller="MyFormCtrl">
<form name="myForm" ng-submit="register()">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter first name" ng-model="user.fname">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter last name" ng-model="user.lname">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter designation" ng-model="user.designation">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter company" ng-model="user.company">
<input type="submit" style="float:right;" value="Register"> </form>
</div>
<div id="box" style="position: relative;top:200px;margin: auto;border:1px solid red;width:180px;height:90px;" ng-controller="DetailsConroller">
<input type="button" ng-click="getDetails()" value="get">
<!-- <input type="submit" style="" value="get">-->
<ul>
<li ng-repeat="x in employees"> {{ x.fname }} </li>
</ul>
</div>
my js:
var app = angular.module('myApp', []);
--->service for adding and get
app.service('employeeService', ['$rootScope', function ($rootScope) {
var employeeList = [];
return {
employeeList: []
, // var employeeList = [],
add: function (item) {
employeeList.push(item);
console.log('employeeList', employeeList);
}
, get: function () {
// console.log('in to get employeeList',employeeList);
return employeeList
}
};
}])
---->> COntroller to Add:
app.controller('MyFormCtrl', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.user = {
fname: ''
, lname: ''
, designation: ''
, company: ''
};
$scope.register = function () {
console.log('User clicked register', this.user);
employeeService.add(this.user);
//employeeService.updateUserData().set($rootScope.user);
};
}]);
--->>second controller to get:
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
var employees = [];
$scope.getDetails = function () {
// console.log('User clicked register', this.user);
employees = employeeService.get();
console.log('User in to get', employees[0].fname);
return employees;
};
}]);
what am I doing wrong here?
You need to have a $scope variable,
Change your Controller like this,
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.employees = [];
// console.log('User clicked register', this.user);
$scope.employees = employeeService.get();
console.log('User in to get', employees[0].fname);
}]);

angularjs with ng-repeat. cant access the data in controler when i use ng-repeat

I use the following ng-model with ng-repeat and I tried to access the data in my controller but it seems that the data cant be accessed there.
<div ng-controller="myCtrl" class="container">
<fieldset data-ng-repeat="contact in choices">
<input class="form-control" ng-model='contact.firstname'>
<input class="form-control" ng-model='contact.lastname'>
<input class="form-control" ng-model='contact.email'>
<input class="form-control" ng-model='contact.contact'>
<input class="form-control" ng-model='contact.adress'>
<input class="form-control" ng-model='contact.city'>
<input class="form-control" ng-model='contact.state'>
<button class="btn btn-primary" ng-click="addcontact()">Add</button></td>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
</div>
</div>
And use the following ng-app
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.choices = [{
id: 'choice1'
}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id': 'choice' + newItemNo
});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length - 1;
$scope.choices.splice(lastItem);
};
var refresh = function() {
$http.get('/contactlist').success(function(response) {
console.log("in m new controler now");
$scope.contactlist = response;
$scope.contact = "";
});
};
refresh();
$scope.addcontact = function() {
console.log($scope.contact);
$http.post('/contactlist', $scope.contact).success(function(response)
{
console.log(response);
refresh();
});
};
});
I can't access the data in $scope for the dynamically added controls through ng-repeat
In order to acess the data you should use
$scope.choices[index]
Index is the number of index you want to acces

Resources