AngularJS Textarea If data Is loading - angularjs

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.

Related

How to get selected option value from dropdown using angular

I have two drop downs with add resource button, when I click add resource button I need to pass selected option values from drop downs into insertResource method.How to get selected option value??I know we can easily do it using option:selected in jquery But I want do it in angular.Any help?
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<div class="row">
<div>
<label class="displayBlock margin">Project Name</label>
<input type="text" name="name" class="currentProjectName">
</div>
<div>
<label class="displayBlock margin">Resource Name</label>
<select name="ResourceInsert" id="allocateResource"><option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option></select>
</div>
<div>
<label class="displayBlock margin">Role Name</label>
<select name="ResourceInsert" id="allocateRole"><option data-ng-repeat="data in roleList" value="{{data.RoleId}}">{{data.RoleName}}</option></select>
</div>
</div>
<div class="row">
<button class="btn btn-primary addResource" ng-click="insertResource()">Add Resource</button>
</div>
</div>
</body>
<script>
var app = angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope,$http) {
$scope.init = function () {
$scope.getProjId();
$scope.ResourceJson();
$scope.RoleJson();
}
$scope.getProjId = function () {
var url = document.URL;
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var projectName = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('.currentProjectName').val(projectName)
}
$scope.ResourceJson = function () {
$http.post('/Project/empList').then(function (response) {
$scope.resourceList = response.data;
console.log($scope.resourceList)
})
}
$scope.RoleJson = function () {
$http.post('/Project/roleList').then(function (response) {
$scope.roleList = response.data;
console.log($scope.roleList)
})
}
$scope.insertResource = function () {
}
});
</script>
If your questions is getting data of selected item of select. It is done as follows using ng-model directive:
<select name="ResourceInsert" id="allocateResource" ng-model="selectedValue">
<option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option>
</select>
In Controller:
console.log($scope.selectedValue, "selected Value"); //Your selected value which is EmpId.

How to dynamically call data from an API when option is selected

Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.
<div class="container">
<div class = "row" ng-controller="reservationCtrl">
<div class="form-group">
<label for="sel1">Select a Hotel:</label>
<select class="form-control" id="sel1">
<option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
</select>
</div>
</div>
And I am using GET method to call data from another API to display the hotel_name.
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data">{{x.hotel_name}}</h1>
</div>
</div>
</div>
Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
angular
.module("reservationModule")
.controller("showCtrl", function($http, $scope, $log){
$http({
method: 'GET',
url: '&hotel_id=72'})
.then(function (response) {
$scope.hotel = response.data;
}, function (reason){
$scope.error = reason.data;
$log.info(reason);
});
});
})();
Here is the reservationController
(function(){
angular
.module("reservationModule")
.controller("reservationCtrl", function($http, $scope, $log){
$http({
url: '',
method: "POST",
data: 'postData',
headers:{ 'Authorization': 'value'}
})
.then(function(response) {
$scope.hotels = response.data;
}
);
});
})();
Yes you can add ng-change and achieve your functionality as below
JS code
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope) {
$scope.hotels = [{
name: 'Taj',
id: 1
}, {
name: 'Royal',
id: 2
}];
$scope.hotelInfo = {};
$scope.fetchData = function() {
// here call service which will fetch data and assign to hotel data
$scope.hotelInfo = {
address: 'London'
};
}
});
app.controller('ctrl2', function($scope) {
$scope.data = ''
});
HTML code
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
<select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
</select>
{{hotel}} - {{hotelInfo}}
</div>
</div>
Here is the link Jsfiddle demo
You need to call event on the select box which will call simple function which return the data like following
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
write javascript code on the update function
Your can use ng-change on select of particular hotel.
In congroller :
$scope.showHotel = function(hotelName){
$scope.selectedHotel = hotelName;
}
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data" ng-change="showHotel(x.hotel_name)">{{x.hotel_name}}</h1>
</div>
</div>
In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1>{{selectedHotel}}</h1>
</div>
</div>

angular js: Unable to validate a textarea

fellas!
I'm trying to validate a text area upon clicking a link. Thing is, It's not coming inside a form. And when a user clicks a link, content entered in the text area should be posted (saved to database).
I wrote a validation for that. And unfortunately, it's not working and I'm able to make blank posts. I'm trying to prevent blank post posting. I have recreated the form and the controller in a fiddle. Link I'll provide down. but before that, take a look at my html and js code.
HTML
<div ng-app="myApp" ng-controller="myMap">
<div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
<textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</div>
JavaScript
angular.module('myApp', [])
.factory('myService', function($http) {
var baseUrl = 'api/';
return {
postCurrentPost: function(newPost) {
var dataPost = {
newPost: newPost
};
return $http({
method: 'post',
url: baseUrl + 'postCurrentPost',
data: dataPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
};
})
.controller('myMap', function(myService, $http, $scope) {
var vm = this;
var userObject;
// Add a post
vm.addPost = function(newPost, isValid) {
if (isValid) {
var currentPost = vm.currentPost;
currentPost.content = ""; //clear post textarea
myService.postCurrentPost(newPost).success(function(data) {
vm.posts = data;
});
} else {
alert('Validation not working');
}
};
//Check validation
$scope.getError = function(error, name) {
if (angular.isDefined(error)) {
if (error.required && name == 'vm.currentPost.content') {
return "This field is required";
}
}
}
});
And here's a FIDDLE.
Name of the form input element should be used instead of model value.
https://docs.angularjs.org/api/ng/directive/form
<div ng-app="myApp" ng-controller="myMap">
<form name="formContent">
<div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
<textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</form>
Content is dirty: {{formContent.content.$dirty}}
<br>
Content has required: {{formContent.content.$error.required}}
</div>

ng-model data not getting when saving the data

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);
}
});

AngularJS ng-repeat and ng-options do not output options in Bootstrap Modal

I try to populate my select options in a bootstrap Modal with ajax json data and having used 2 workarounds but non of outputs data
first markup with ng-repeat
<div class="form-group" ng-show="formInfo.sourceType =='api'">
{{ API }}
<label for="selectAPI" class="col-sm-2 control-label">Select API</label>
<div class="col-sm-8">
<select ng-model="selectedAPI" class="form-control">
<option value="{{item.id}}" ng-repeat="(i,item) in networks"> {{item.name}}</option>
</select>
<pre>{{ networks }}</pre>
</div>
Second with ng-options
<div class="form-group" ng-show="formInfo.sourceType =='api'">
{{ API }}
<label for="selectAPI" class="col-sm-2 control-label">Select API</label>
<div class="col-sm-8">
<select ng-model="selectedAPI" ng-options="item.name for item in networks" class="form-control"> </select>
<pre>{{ networks }}</pre>
</div>
Controller
$request('onAPI', {success: function(data, scope){
this.success(data).done(function() {
$scope.networks = [];
$scope.networks = angular.fromJson(data.result);
$scope.selectedAPI = null;
//$scope.selectedAPI = $scope.apis[0];
console.log($scope.networks); // I have output
});
}
});
the response json
[{
"id":"1",
"name":"Zanox"
},{
"id":"2",
"name":"Affilinet",
}]
Got it working
var ModalInstanceCtrl = function ($scope, $modalInstance, items, $request) {
$scope.items = items;
$request('onAPI', {success: function(data, scope){
this.success(data).done(function() {
$scope.networks = [];
$scope.networks = angular.fromJson(data.result);
$scope.selectedAPI = null;
//$scope.selectedAPI = $scope.apis[0];
console.log($scope.networks);
});
}
});
};
Try this
<select ng-model="selectedAPI" class="form-control"
ng-options = "item.name as item.name for item in networks" >
</select>
First, your ng-model selectedAPI seems to have no value, and then it will create a blank option by default.
Second, when using the ajax for asynchronous http request, the response might be not generated on time. So you can use the $scope.$apply method to force a AngularJS data-reload. Like:
$request('onAPI', {success: function(data, scope){
this.success(data).done(function() {
$scope.$apply(function(){
$scope.networks = [];
$scope.networks = angular.fromJson(data.result);
$scope.selectedAPI = null;
//$scope.selectedAPI = $scope.apis[0];
console.log($scope.networks); // I have output
});
});
}
});
Please let me whether it works. Thanks.

Resources