How to get selected option value from dropdown using angular - angularjs

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.

Related

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.

How to handle multiple forms present in a single page using AngularJS

I am a newbie in AngularJS. I am having multiple forms on a single page which gets displayed based on the user selection only one at a time.
The DOM has two child controllers namely FirstFormController, SecondFormController wrapped under a parent controller named XceptionController.
A parent controller function is used to submit the form data from both the children. The form data is saved on to the parent controller's scope.My HTML looks like below
<div ng-app="app">
<div class="container" ng-controller="XceptionController">
<form class="form-container">
<select id="select-form" ng-change=selectForm() ng-model="selectedForm">
<option value="select" disabled selected>Select an Option</option>
<option value="firstform">Get Firstname</option>
<option value="secondform">Get Lastname</option>
</select>
</form>
<div ng-controller="FirstFormController" class="firstform" ng-show="fname">
<form name="firstnameform">
<input type="text" name="firstname" ng-model="form.firstname" id="firstname">
<label for="#firstname">Firstname</label>
</form>
<div class="content" ng-show="fname">
<p>Firstname is {{form.firstname}}</p>
</div>
</div>
<div ng-controller="SecondFormController" class="secondform" ng-show="lname">
<form name="lastnameform">
<input type="text" name="lastname" ng-model="form.lastname" id="lastname">
<label for="#lastname">Lastname</label>
</form>
<div class="content" ng-show="lname">
<p>Lastname is {{form.lastname}}</p>
</div>
</div>
<button ng-click="submitForm(form)">Submit</button>
And my js looks like
var app = angular.module('app', []);
app.controller('XceptionController', function($scope){
$scope.form = {};
$scope.selectedForm = '';
$scope.selectForm = function() {
$scope.lname = 0;
$scope.fname = 0;
var foo = angular.element(document.querySelector('#select-form')).val();
if(foo == 'firstform') {
$scope.fname = 1;
}
else if(foo == 'secondform'){
$scope.lname = '1';
}
};
$scope.submitForm = function(form){
//form data
console.log(form);
};
});
app.controller('FirstFormController', function($scope){
$scope.firstname = "";
});
app.controller('SecondFormController', function($scope){
$scope.lastname = "";
});
But on submitting the form I get the data from both the forms since I set it on the parent's scope. Is there a way by which I can submit the form and get the form data only for the form which is currently displayed. This fiddle will help you more in understanding my question. https://jsfiddle.net/xmo3ahjq/15/
Also help me in knowing if my code is properly written the way it should be or is there a better way to implement this. Should the form submission code be placed under a separate angular service ?
var app = angular.module('app', []);
app.controller('XceptionController', function($scope) {
$scope.form = {};
$scope.selectedForm = null;
$scope.selectForm = function() {
// reset the form model object
$scope.form = {};
};
$scope.isSelected = function(formName) {
return $scope.selectedForm === formName;
};
$scope.submitForm = function(form) {
// form data
console.log(form);
};
});
app.controller('FirstFormController', function($scope) {
});
app.controller('SecondFormController', function($scope) {
});
<div ng-app="app">
<div class="container" ng-controller="XceptionController">
<form class="form-container">
<select id="select-form" ng-change=selectForm() ng-model="selectedForm">
<option value="" disabled selected>Select an Option</option>
<option value="firstform">Get Firstname</option>
<option value="secondform">Get Lastname</option>
</select>
</form>
<div ng-controller="FirstFormController" class="firstform" ng-show="isSelected('firstform')">
<form name="firstnameform">
<input type="text" name="firstname" ng-model="form.firstname" id="firstname">
<label for="#firstname">Firstname</label>
</form>
<div class="content">
<p>Firstname is {{form.firstname}}</p>
</div>
</div>
<div ng-controller="SecondFormController" class="secondform" ng-show="isSelected('secondform')">
<form name="lastnameform">
<input type="text" name="lastname" ng-model="form.lastname" id="lastname">
<label for="#lastname">Lastname</label>
</form>
<div class="content">
<p>Lastname is {{form.lastname}}</p>
</div>
</div>
<button ng-click="submitForm(form)">Submit</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

AngularJS: Only post non-blank values

I am trying to $http.post a JSON object from a form. I can't seem to find the right syntax. Let's assume my form only takes one value (name). I use ng-model to bind the name to an object called modcampaign.name.
What's the correct syntax to post this to a http service?
Further, what if I had another input box, Description, and only want to bind this to modcampaign.description if the user entered data in the input box? If the input box is empty, I'd like to take the value for .description from another object (like modcampaign2.description).
<form ng-submit="modifyCampaign(selCampaign, newName)" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
</div>
</div>
</form>
This is the script file:
var myApp = angular.module('myApp', []);
myApp.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/campaigns.json').success(function (data) {
$scope.campaigns = data;
});
$http.post('js/campaign_mod.json').success(function (data) {
data = $scope.modCampaign;
});
$scope.selCampaign={};
$scope.selectCampaign = function (campaign) {
$scope.toggleCampaign = !$scope.toggleCampaign;
$scope.selCampaign = campaign;
};
$scope.abbrechen = function () {
$scope.toggleCampaign = !$scope.toggleCampaign;
};
$scope.submit = function () {
$http.post('')
}
}]);
You can include something like this in your controller:
$scope.modCampaign = {};
//this gets called on ng-submit
$scope.submitData = function(){
$http.post("api-end-point", $scope.modCompaign).success(function(data, status) {
//handle response etc.
});
}
Your html will have something like this:
<form ng-submit="submitData()" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
<textarea ng-model="modCampaign.description"/></textarea>
</div>
</div>
</form>
you can use JSON.stringify()
example
$http({
method: "POST",
url: 'http://www.example.com/posturl',
data : JSON.stringify($scope.modcampaign)
}).success(function(response){
console.log(response);
// write any action after post success
})
<form ng-submit="modifyCampaign(modCampaign)" class="form-horizontal" name="modCampaign">
<!-- Modify Name -->
<div class="form-group">
<label class="col-lg-2 control-label" for="modName">Name</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modName" ng-model="modCampaign.name"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="modDescription">Description</label>
<div class="col-lg-8">
<input class="form-control" type="text" id="modDescription" ng-model="modCampaign.description"/>
</div>
</div>
</form>
var myApp = angular.module('myApp', []);
myApp.controller('ListController', ['$scope', '$http', function($scope, $http) {
$scope.modifyCampaign = function(modCampaign) {
console.log(modCampaign)
alert(modCampaign.name) // name:"jane"
alert(modCampaign.description) // description: "hello"
$http.post('js/campaign_mod.json', { name: modCampaign.name, description: modCampaign.description }).success(function (data) {
console.log(data)
});
}
}]);
This method lets you bind all the form value to one object and then you can decode the value in your controller file, below is a link to a working example
http://codepen.io/anon/pen/VjYLvg

Angularjs List/Detail Edit

I am writing a small AngularJS/Ionic/Cordova application where I have a list of contacts. When the user taps on a contact, I navigate to a new page where details about the contact are shown (first name, last name, phone number). Here, the user can update details about the contact, or delete the contact. The problem I have is when the user deletes the contact the list still shows the deleted item after navigating back.
Right now I am storing the list of contacts in localStorage, but I do plan on eventually persisting these values in SQLite and/or a web service.
I am using two controllers, two html templates, and a factory. Why is the first list not updating when I make changes to a detail item? I am very new to AngularJS so please bear with me.
List Controller
angular
.module('app')
.controller('contactListCtrl', ['$scope', 'Contacts',
function($scope, Contacts) {
$scope.contacts = Contacts.get();
}
])
List Template
<ion-content scroll="false" class="padding-horizontal" has-header="true">
<div class="row padding-vertical">
<div class="col col-center text-center">
<span class="small-text primary-text-color">Contact List</span>
</div>
</div>
<div class="row" >
<div class="col col-center">
<ul class="list">
<li class="item" ng-repeat="contact in contacts" ui-sref="contactListEdit({id: $index})">
{{contact.fName}} {{contact.lName}}
</li>
</ul>
</div>
</div>
</ion-content>
Detail Controller
angular
.module('app')
.controller('editContactCtrl', ['$scope', '$stateParams', 'Contacts',
function($scope, $stateParams, Contacts) {
var contactId = false;
if ($stateParams.id !== 'undefined') {
contactId = $stateParams.id;
}
$scope.contact = Contacts.get(contactId);
$scope.contactId = contactId;
$scope.delete = function(index) {
Contacts.removeContact(index);
window.history.back();
};
}
])
Detail Template
<ion-content scroll="false" class="padding-horizontal" has-header="true">
<div class="row padding-vertical">
<div class="col col-center text-center">
<span class="medium-text primary-text-color">Edit contact</span>
</div>
</div>
<div class="list">
<label class="item item-input">
<input type="text" placeholder="First Name" ng-model="contact.fName">
</label>
<label class="item item-input">
<input type="text" placeholder="Last Name" ng-model="contact.lName">
</label>
<label class="item item-input">
<input type="text" placeholder="Phone" ng-model="contact.mobile">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="contact.email">
</label>
<button ng-click="save()" class="button button-full button-positive">
Save
</button>
<button ng-click="delete(contactId)" class="button button-full button-assertive">
Delete
</button>
</div>
</ion-content>
Contacts Factory
angular
.module('app')
.factory('Contacts', ['$http',
function($http) {
return {
get: function(index) {
var contacts;
try {
contacts = JSON.parse(window.localStorage.getItem("contacts"));
if (index >= 0) {
return contacts[index];
}
return contacts;
} catch (e) {
console.log("error parsing json contacts");
return false;
}
},
removeContact: function (index) {
var contactList = this.get();
if (index !== -1) {
contactList.splice(index, 1);
}
console.log(contactList);
this.saveContacts(contactList);
},
setDefaultContacts: function() {
var self = this;
return $http.get('./mock_data/contacts.json').then(function(response) {
// contacts already exist, don't set.
if (window.localStorage.getItem("contacts")) {
return false;
} else {
self.saveContacts(response.data);
return true;
}
});
},
saveContacts: function(contactList) {
window.localStorage.setItem("contacts", JSON.stringify(contactList));
},
};
}
])
I think you will find that the contactListCtrl is not being setup again when you navigate back to it (after a delete). I believe this is because Ionic caches views for you.
What you need to do is listen to $ionicView.beforeEnter event and load your contacts list into your ContactListCtrl scope whenever you receive this event.
So.. Try adding something like this to your controller:
$scope.$on('$ionicView.beforeEnter', function() {
$scope.contacts = Contacts.get();
}
);
Check out: http://ionicframework.com/blog/navigating-the-changes/

AngularJS : Hide and show radio button

<div class="filter_hide">
<div ng-cloak ng-repeat="web in website" >
<label ng-show="filter[web.websiteId]"><input type="radio" id="{{web.websiteId}}" ng-checked="webCheck" id="{{web.websiteId}}" value="{{web.websiteId}}" name="webname" ng-model="filter[web.websiteId]" />{{web.websiteName}} ({{web.couponCount}})</label>
</div>
</div>
<div class="filter_show">
<div class="check_box" ng-hide="filter[web.websiteId]" ng-repeat="web in website">
<label><input type="radio" value="{{web.websiteId}}" ng-checked="webCheck" id="{{web.websiteId}}" name="webname" ng-click="webcall(web)" ng-model="filter[web.websiteId]" />{{web.websiteName}} ({{web.couponCount}})</label>
</div>
</div>
I am trying to make when some one click on radio button form "filter_show" div then need to hide form there and show on "filter_hide" div and if user again click another radio button form "filter_show" div then need to hide previously select radio button form "filter_hide" div and show new one there.
I am using angular js 1.2.17
my controller -
app.controller('myCtrl', function ($scope, $http) {
$http({method: 'GET', url: '/asasa/asa/'}).success(function(data) {
$scope.website = data.websites;
$scope.onlinedata = data.coupons;
$scope.restdata = $scope.onlinedata;
$scope.webcall = function (web) {
$http({method: 'GET',url: '/asas/cccc/asas?websiteId='+web.websiteId}).success(function(data) {
$scope.onlinedata = data.coupons;
});
};
Take a look a this example
fiddle Example
<div ng-app>
<div ng-controller='contorller'>
<div class='to_hide' ng-if='hide === true'>
<input type="radio" name='hide' ng-click="showElement('show')" />Hide<br>
<input type="radio" name='hide' ng-click="showElement('show')" />Hide<br>
</div>
<br>
<div clas='to_show' ng-if='hide === false'>
<input type="radio" name='show' ng-click="showElement('hide')" />Show</br>
<input type="radio" name='show' ng-click="showElement('hide')" />Show</br>
</div>
</div>
</div>
<script>
function contorller($scope){
$scope.hide = true;
$scope.showElement = function(value){
if(value === 'hide'){
$scope.hide = true;
}else{
$scope.hide = false;
}
}
}
</script>

Resources