AngularJS: Only post non-blank values - angularjs

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

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 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.

Need to filter model based on make in angularjs. below code is not working model comes empty if filtered on make

Need to Filter options in dropdown based on manufacturers (make). Need to filter models based on selected make option via "ng-model:make"
HTML:
<div class="form-group">
<label for="make">Make</label>
<select class="form-control" data-ng-model="make" data-ng-options="maker.make for maker in makers" required></select>
</div>
<div class="form-group">
<label for="make">Make</label>
<select class="form-control" data-ng-model="make" data-ng-options="maker.make for maker in makers" required></select>
</div>
<div class="form-group">
<label for="model">Model</label>
<select class="form-control" data-ng-model="model" data-ng-options="availabledevice.model for availabledevice in availabledevices|filter:make" required></select>
</div>
Services from factory:
deviceassign.factory("manufacturersoptionsservice", function($http) {
var devicemakers = {};
devicemakers.values = function() {
return $http.get('api/displaymanufacturersapi.php');
}
return devicemakers;
});
deviceassign.factory("availabledeviceservice", function($http) {
var availabledevice = {};
availabledevice.details = function() {
return $http.get('api/displayavailabledevicesforoptionsapi.php');
}
return availabledevice;
});
Controller:
deviceassign.controller('assigndevicecontroller', function($scope, growl, manufacturersoptionsservice, availabledeviceservice) {
manufacturersoptionsservice.values().success(function(response1) {
$scope.makers = response1;
});
availabledeviceservice.details().success(function(response3) {
$scope.availabledevices = response3;
});
// ...
});
Its working now.Had to select make.make as make itself is an object in JSON
<select class="form-control" data-ng-model="model" data-ng-options="availabledevice.model for availabledevice in availabledevices|filter:make.make" required></select>

Post angularjs form to nodejs Express ( Bad request)

im new in angularJs, im trying to make a basic login with angularJS and nodejs ( server side), i dont care about security for now im just trying to learn how to post. so i made a login form and a controller with angular :
My Login Form :
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="login.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="login.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login()">Login</button>
</div>
</form>
</div>
then my router & controller Angularjs :
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
});
}])
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.login = function() {
$http.post('/api/users/login', $scope.login).success(function (response) {
console.log(response);
// refresh();
});
};
}]);
and Server side i have that :
router.post('/login/', function(req, res) {
// here "/login/" means "/users/login" ( in index of controllers)
console.log(req.body.mail);
var usermail = req.body.mail;
var pass = req.body.password;
console.log(usermail + pass);
User.find({mail: usermail}, function(err, user) {
if (err) {
res.send(err);
console.log("ça marche pas")
} else {
res.json( user );
console.log(user);
}
})
});
server side : it works ( when i use DHC chrome extension to Post) but when im using angularjs view i got that error :
POST http://localhost:3000/api/users/login 400 (Bad Request)
Please help me to solve that, i think i missed something. Thank you in advance.
I think you are sending your login function as in below line:
$http.post('/api/users/login', $scope.login)
You probably want to pass a parameter in your login function that can be sent to server as below:
$scope.login = function(loginData) {
$http.post('/api/users/login', loginData).success(function (response)
Update
You are assigning your form values to $scope.login. If you would create a separate variable for it, for example loginForm, you can send this as valid JSON to your API:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="loginForm.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="loginData.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login(loginData)">Login</button>
</div>
</form>
</div>
And .js:
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loginForm = {
mail: '',
password: ''
};
$scope.login = function(loginData) {
// Check what this prints out:
console.log(loginData);
$http.post('/api/users/login', loginData).success(function (response) {
console.log(response);
// refresh();
});
};
}]);

Not getting Live Preview for Angular Text Area

I have angular 1.5 Version. The Text Area is not giving the live preview. I've written ng-model and written controller code, now I have no idea what is missing in it.
Controller Code:
(function() {
var app = angular.module('wildfire', []);
var updateStatusText = 'test';
app.controller('UpdateStatusController', function() {
this.message = updateStatusText;
this.updateStatus = function(text) {
var StatusObject = {};
updateStatusText = text;
}
});
}
HTML Code:
<div class="well">
<form class="form-horizontal" role="form" ng-controller="UpdateStatusController as statusUpdate" ng-submit="statusUpdate.updateStatus(statusUpdate.message)">
<h4>What's New</h4>{{statusUpdate.message}}
<div class="form-group" style="padding:14px;">
<textarea class="form-control" ng-model "statusUpdate.message" placeholder="Update your status"> </textarea>
{{statusUpdate.message}}
</div>
</div>
Its not giving the live preview and after submitting it does not send any value associated with the TextArea. I debugged it several time but no result totally frustrating.
Change this
ng-model "statusUpdate.message"
To this
ng-model = "statusUpdate.message"
Complete example
<div class="well">
<form class="form-horizontal" role="form" ng-controller="UpdateStatusController as statusUpdate" ng-submit="statusUpdate.updateStatus(statusUpdate.message)">
<h4>What's New</h4>{{statusUpdate.message}}
<div class="form-group" style="padding:14px;">
<textarea class="form-control" ng-model= "statusUpdate.message" placeholder="Update your status"> </textarea>
{{statusUpdate.message}}
</div>
</div>
angular.module('wildfire', []).controller('UpdateStatusController',['$scope', '$http', function($scope, $http){
var updateStatusText = 'test';
this.message = updateStatusText;
this.updateStatus = function(text) {
var StatusObject = {};
updateStatusText = text;
}
}]);

Resources