AngularJs Expression not working - angularjs

I have a weird issue with the {{json_req}} expression, the {{pseudo}} and {{password}} expression are working well, I can see the changes I make in live.
But nothing happened for the {{json_req}} expression, no matter what I write on the Login and Password input.
I guess It's a basic mistake by me but I'm a little lost with this one right now :/.
Thanks for the help :)
Login.html
<div class="row">
Pseudo : {{pseudo}}
</div>
<div class="row">
Password : {{password}}
</div>
<div class="row">
json : {{json_req}}
</div>
<div class="row">
<label class="float-center">
Pseudo
<input ng-model="pseudo" type="text" required>
<span class="form-error">
Pseudo Missing.
</span>
</label>
</div>
<div class="row">
<label class="float-center">
Password
<input ng-model="password" type="password" required>
<span class="form-error">
Password Missing.
</span>
</label>
</div>
LoginCtrl.js
mCtrl.controller('LoginCtrl', ['$scope', 'User', function ($scope, User) {
$scope.json_req = {
pseudo: $scope.pseudo,
password: $scope.password
};
$scope.LoginUser = function () {
if ($scope.json_req.pseudo != undefined && $scope.json_req.password != undefined) {
User.login($scope.json_req).then(function (data) {
$scope.response = data;
$scope.json_req = {};
});
} else
console.log("UNDEFINED");
};
}]);

This is expected behaviour. When you write:
$scope.json_req = {
pseudo: $scope.pseudo,
password: $scope.password
};
you create a "snapshot" of the values for $scope.pseudo and $scope.password. They will not update when you change model later.
You could setup a $scope.$watch and update json_req when either of pseudo or password changes (not really recommended). Or what I would recommend, write a getter function on the scope:
Object.defineProperty($scope, 'json_req', {
get: function() {
return {
pseudo: $scope.pseudo,
password: $scope.password
}
}
});

Try this:
angular.module("asdfapp",[]).service("User",function(){}).controller('LoginCtrl', ['$scope', 'User',
function ($scope, User) {
$scope.json_req = {
pseudo: "",
password: ""
};
$scope.LoginUser = function () {
if ($scope.json_req.pseudo != undefined
&& $scope.json_req.password != undefined) {
User.login($scope.json_req).then(function (data) {
$scope.response = data;
$scope.json_req = {};
});
} else
console.log("UNDEFINED");
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="asdfapp" ng-controller="LoginCtrl">
<div class="row">
Pseudo : {{json_req.pseudo}}
</div>
<div class="row">
Password : {{json_req.password}}
</div>
<div class="row">
json : {{json_req}}
</div>
<div class="row">
<label class="float-center">
Pseudo
<input ng-model="json_req.pseudo" type="text" required>
<span class="form-error">
Pseudo Missing.
</span>
</label>
</div>
<div class="row">
<label class="float-center">
Password
<input ng-model="json_req.password" type="password" required>
<span class="form-error">
Password Missing.
</span>
</label>
</div>
</div>

Ok I find the solution. And is expected It was a stupid mistake from me xD
I should write ng-model="json_req.pseudo" and not ng-model="pseudo" to fill the json_req object :/
Sorry to have bothered you guys !
Thanks

Related

Send/Add CVV/CVN Field on Cybersource Flex Microform

I am using Flex Microform and was able to successfully render the Credit Card Iframe from Cybersource.
Now, the question is to Add/Send CVN/CVV details along with above request.
In the document, we can pass only three parameters in the createToken Method - CardType, CardExpirationYear, and CardExpirationMonth.
I couldn't find anything about sending/Adding CVN.
Please guide if anyone has done similar implementation where we can send CVN details from the Flex Form.
Html
---
<label id="cardNumber-label">Card Number</label>
<div id="number-container" class="form-control"></div>
<label for="securityCode-container">Security Code</label>
<div id="securityCode-container" class="form-control"></div>
--
</div>
<div class="form-row">
----
</form>
Js
var flex = new Flex(captureContext);
var microform = flex.microform({ styles: myStyles });
var number = microform.createField('number', { placeholder: 'Enter card number' });
var securityCode = microform.createField('securityCode', { placeholder: '•••' });
number.load('#number-container');
securityCode.load('#securityCode-container');
Ref: developer-guides
I think this is what you're looking for
https://developer.cybersource.com/docs/cybs/en-us/digital-accept-flex/developer/all/rest/digital-accept-flex/microform-integ/api_reference/class_Microform.html
Example:
<div class="container card">
<div class="card-body">
<h1>Checkout</h1>
<div id="errors-output" role="alert"></div>
<div class="form-group">
<label for="cardholderName">Name</label>
<input id="cardholderName" class="form-control" name="cardholderName" placeholder="Name on the card">
<label id="cardNumber-label">Card Number</label>
<div id="number-container" class="form-control"></div>
<label for="securityCode-container">Security Code</label>
<div id="securityCode-container" class="form-control"></div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="expMonth">Expiry month</label>
<select id="expMonth" class="form-control">
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="expYear">Expiry year</label>
<select id="expYear" class="form-control">
<option>2022</option>
<option>2023</option>
</select>
</div>
</div>
</div>
</div>
<script src="https://flex.cybersource.com/cybersource/assets/microform/0.11/flex-microform.min.js"></script>
<script>
$(document).ready(function() {
$('#submission-form').submit(function(e) {
e.preventDefault();
});
var form = document.querySelector('#submission-form');
var payButton = document.querySelector('#btnPay');
var flexResponse = document.querySelector('#SecureToken');
var expMonth = document.querySelector('#expMonth');
var expYear = document.querySelector('#expYear');
var errorsOutput = document.querySelector('#errors-output');
// the capture context that was requested server-side for this transaction
var captureContext = /*caputre context loaded here*/ ;
// setup
var flex = new Flex(captureContext);
var number = microform.createField('number', {
placeholder: 'Enter card number'
});
var securityCode = microform.createField('securityCode', {
placeholder: '•••'
});
number.load('#number-container');
securityCode.load('#securityCode-container');
payButton.addEventListener('click', function() {
var options = {
expirationMonth: expMonth.value,
expirationYear: expYear.value
};
microform.createToken(options, function(err, token) {
if (err) {
// handle error
} else {
flexResponse.value = JSON.stringify(token);
form.submit();
}
});
});
});
</script>

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.

value in my array changes but i don't know how to find where it is being changed

So, i have this problem where a property in my array collection changes. Here is the code snippet for my controller:
$http({
method: 'GET',
headers: globalData.httpHeader,
params: {
orderkey:$scope.transaction.orderData.orderkey,
category:'ViewOrderDetail'},
url: globalData.APIARN+ globalData.StageVariable + globalData.OrderRes
}).then(function successCallback(response) {
$ionicLoading.hide();
if (response.data.errorMessage) {
swal({
title: "Ooops!",
text: "Problem Encountered in the Server. Please Contact Support."
});
} else {
$scope.itemDetails =response.data.order.orderdetail;
$scope.items = $scope.itemDetails;
angular.forEach($scope.itemDetails, function(value, key) {
$scope.itemKeys.push(value.productKey);
$scope.itemKey = $scope.itemKeys[$scope.itemKeys.length - 1];
$scope.itemKey++
$scope.itemAmountValues.push(value.quantity * value.unitPrice)
});
}
$scope.calcTotalAndProductAmt();
$scope.showItem = function(selectedKey){
$scope.selectedKeyItems = [];
angular.forEach($scope.itemDetails, function(value, key) {
if(value.itemKey == selectedKey){
$scope.selectedKeyItems.push(value)
}
});
}
console.log("before " + JSON.stringify($scope.items));
$timeout(function(){
console.log("after " + JSON.stringify($scope.items));
})
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$ionicLoading.hide();
$scope.messageText = globalData.ProblemLoad;
swal({
title: "Ooops!",
text: $scope.messageText
});
}); // $http call
Now, the console log result shows the following:
before [{"id":95,"productKey":"19","productName":"Roast Chicken","quantity":2,"unitPrice":175,"itemStatus":"OPEN"},{"id":96,"productKey":"14","productName":"Bolognese","quantity":3,"unitPrice":225,"itemStatus":"OPEN"},{"id":97,"productKey":"16","productName":"Coke","quantity":4,"unitPrice":50,"itemStatus":"CLOSE"},{"id":98,"productKey":"22","productName":"Rice","quantity":2,"unitPrice":45,"itemStatus":"OPEN"}]
transaction.js:1149
after [{"id":95,"productKey":"19","productName":"Roast Chicken","quantity":2,"unitPrice":175,"itemStatus":"OPEN","$$hashKey":"object:103"},{"id":96,"productKey":"14","productName":"Bolognese","quantity":3,"unitPrice":225,"itemStatus":"OPEN","$$hashKey":"object:104"},{"id":97,"productKey":"16","productName":"Coke","quantity":4,"unitPrice":50,"itemStatus":"OPEN","$$hashKey":"object:105"},{"id":98,"productKey":"22","productName":"Rice","quantity":2,"unitPrice":45,"itemStatus":"OPEN","$$hashKey":"object:106"}]
As you can see, the itemStatus for Coke changes from "CLOSED" to "OPEN". However, i don't know how the value changes since my controller does not have a code that changes this. My html looks like this:
<div class="row" ng-repeat="item in items">
<div class="col col-60" ng-show="item.itemStatus='OPEN'" >
{{item}}
<label class="item item-input">
<select ng-model="item.productKey" ng-change="addPriceEdit(item)" ng-required="true">
<option ng-repeat="item in productskey" value="{{item.productkey}}" >{{item.productname}}</option>
</select>
</label>
</div>
<div class="col col-15">
<label class="item item-input">
<input type="number" ng-model="item.quantity" min="1" step="1" max="9999999999" ng-required="true" ng-change="calcTotalAndProductAmt()">
</label>
</div>
<div class="col col-15">
<label class="item ">
{{item.unitPrice}}
</label>
</div>
<div class="col col-10">
<button class="button button-assertive"
ng-disabled="item.itemStatus!='OPEN'"
ng-click="removeItem($index)">-</button>
</div>
</div>
Anyone has an idea on what's wrong?
Replace your code with -
<div class="col col-60" ng-show="item.itemStatus=='OPEN'" >
Because , with single = , you are assigning value to the variable(so for each object it will change itemstatus to open) . For comparing , you should use ==.

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

Error in ajax call using angular js

I am new to angular js .I tried making a small program that consists of ajax call using angular js $http .I guess I am some where wrong ,doing some mistake.
Would be happy If someone helps out. Following is code snippet
login.html
<head></head>
<body>
<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
<div ng-hide="var">
<h2><center>SIGN-IN</center></h2>
<p>Username:
<br>
<input type="text" name="user" ng-model="user" required><span style="color:red" ng-show="myForm.user.$error.required" />Username is required</p>
<p>Password:
<br>
<input type="password" name="password" ng-model="password" required /> <span style="color:red" ng-show="myForm.password.$error.required">Password is required.</span>
<p>
<input type="submit" ng-click="validate()" ng-disabled=" myForm.user.$invalid ||
myForm.password.$invalid" />
</p>
</div>
<div ng-hide="welcomeVar"> <span> {{ listOfCustomers }} </span>
<h2><center>Welcome! {{ user }}</center></h2>
<button class="list" ng-click="customerList()">List of Customers</button>
<ul>
<li ng-repeat="x in listOfCustomers">{{ x.CustomerID + ', ' + x.CompanyName }}</li>
</ul>
<br>
<button class="signout" ng-click="validate()">Log Out</button>
</div>
</form>
JS part:
<script>
function validateCtrl($scope, $http) {
$scope.user = 'ABC XYZ';
$scope.password = 'abcbc';
$scope.welcomeVar = true;
$scope.
var = false;
$scope.validate = function() {
$scope.
var = !$scope.
var;
$scope.welcomeVar = !$scope.welcomeVar
};
$scope.listOfCustomers = null;
$scope.customerList = function() {
$http.get("http://www.iNorthwind.com/Service1.svc/getAllCustomers")
.success(function(data) {
$scope.listOfCustomers = data;
})
.error(function(data) {
$scope.user = 'Xyz';
});
};
}
</script>
Your code is fine, except some syntax errors, but I hope it's because you tried to remove somrthing before posting code here ;)
Also the response for your request have this structure: {GetAllCustomersResult : [//here an array of elements]} , so, in success response handler you'll have to do: $scope.listOfCustomers = data.GetAllCustomersResult ;
But it's a minor things, the main issue described here:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
To debug this, you had to open developer tools in any browser('F12' is common key to open it), and look in console and network requests.

Resources