i am using this code to get result using AngularJS
<div ng-repeat="item in CartItems" class="row">
<input type="hidden" ng-init="cart.premium[$index] = item.bid_amount" ng-model="cart.premium[$index]">
</div>
In controller
app.controller('ShoppingCart', function($scope, MenuData, $rootScope, $http, RouteData, MyCache) {
$scope.route = RouteData.url;
$scope.user_detail = $rootScope;
var total = 0;
// Cached data
$scope.msg = 1;
$scope.CartItems = MyCache.get('CartItems');
$scope.total = MyCache.get('total');
$scope.itemsCount = MyCache.get('itemsCount');
// data is not in cache then get from server
if(!$scope.CartItems) {
};
$scope.cart = {};
$scope.check_out = function(){
if($scope.cart.total <= 9999){
alert($.param($scope.cart));
PayPalMobile.renderSinglePaymentUI($scope.createPayment1($scope.cart.total), $scope.onSuccesfulPayment, $scope.onUserCanceled);
}
};
but it cannot give any result. While when we do
<input type="hidden" name="test[]" value="test">
give the required result.
How can I achieve this thing with AngularJS?
Related
I'm trying to use angularjs to create a page that does the following:
Is initially empty, save for a dropdownlist that is automatically
populated with apps.
upon selecting one of those apps, data about it will be called from
another controller to the page.
I was successfully able to get the dropdownlist to automatically populate. however, I'm having issues getting it to make the page with ng-change, which I thing is due to the nested ng-controllers. The chartappsuccessfullogins function is not being called at all in my browser. Can anyone help me? Code is below:
My main html page. Note the use of ng-init:
<div ng-controller="chartsuccessfulapploginsController">
<div ng-controller="allappsController" ng-init="add()">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect" ng-change="chartsuccessfulapploginsController.add(value)">
<option ng-repeat="option in data.availableOptions" ng-init="Index = $index" value="{{data.availableOptions[Index].id}}" ng-model="APPID" >{{data.availableOptions[Index].name}}</option>
</select>
</form>
<hr>
<p> {{data}}</p>
<p> {{data.id[0]}}</p>
<p> {{data.name[0]}}</p>
<tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
</div>
<p>{{returnCount}}</p>
<table border = "1">
<tr>
<td>{{chartObject.data}}</td>
<td>{{returnCount}}</td>
</tr>
</table>
<div google-chart chart="chartObject" style="height:600px; width:100%;"></div>
</div>
My get all apps controller. The html page above relies on this to populate the dropdownlist.
angular.module('scotchApp').controller('allappsController',['$scope', function($scope){
var userurl='';
$scope.add = function(){
userurl = 'http://localhost:8085/rest/uafapp/appslist';
var userdata = {};
var userconfig =
{
headers: {
'Content-Type':'application/json'
}
};
var userPostRequest = $.get(userurl, userdata, userconfig);
var userjson = '{\"USER_DATA_RETRIEVED\" : \"fail\"}';
userPostRequest.done(function(userdata){
userjson = JSON.stringify(userdata);
console.log("userjson :: " + userjson);
var postResponse = jQuery.parseJSON(userjson);
$scope.returnName = postResponse['apps'];
var availableOptionsArray = [];
for(i = 0; i < postResponse['apps'].length; i++){
var availableOptions = {};
availableOptions['id'] = postResponse['apps'][i]['appId'];
availableOptions['name'] = postResponse['apps'][i]['appName'];
availableOptionsArray[i] = availableOptions;
}
var returnData = {};
returnData['repeatSelect'] = null;
returnData['availableOptions'] = availableOptionsArray;
$scope.data = returnData;
console.log($scope.returnData);
$scope.$apply()
});
};
}]);
Part of the controller that defines the chart. It's pretty long, so I didn't include the irrelevant code.
angular.module('scotchApp').controller('chartsuccessfulapploginsController',['$scope','$route','$http','AuthTokenService', function($scope, $route, $http, AuthTokenService){
var appurl = '';
var failedappurl= '';
$scope.add = function(APPID) {
...}
Is your allappsController within your chartsuccessfulapploginsController in your controller file?
It should be inside because allappsController is the child scope, and chartsuccessfulapploginsController is the parent scope. You are trying to access the parent scope from the child scope.
If it is not inside, it thinks that ng-change="chartsuccessfulapploginsController.add(value)" is a new controller.
If that is the issue, the fix would be something like this:
angular.module('scotchApp').controller('chartsuccessfulapploginsController',['$scope','$route','$http','AuthTokenService', function($scope, $route, $http, AuthTokenService){
var appurl = '';
var failedappurl= '';
$scope.add = function(APPID) {} ...
//allappsController inside chartsuccessfulapploginsController
angular.module('scotchApp').controller('allappsController',['$scope',function($scope){
var userurl='';
$scope.add = function(){ ... };
}]);
}]);
Check this out: Use ng-model in nested Angularjs controller
I would like to access the input field value inside a variable that could be used in AngularJS so that I could add it to a string with the help of which I could call a rest api.
kindly help.
<body ng-app="myApp">
<div ng-controller="myCtr">
<form name="myForm">
<input type="text" ng-model='pinCode' id="zip" onBlur="myZipcode">
{{city}}
{{state}}
</form>
</div>
<script>
var zip;
var pat1;
function myZipcode(){
zip = document.getElementById("zip").value;
pat1 = 'http://ziptasticapi.com/'+zip;
}
var myApp = angular.module('myApp' , []);
myApp.controller('myCtr', function($scope, $http){
var path = 'http://ziptasticapi.com/12345'
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;});
});
</script>
</body>
Here in http.get service if I use path variable instead of pat1 it works.
Another thing that I want the state and city to come dynamically without the form to be submitted and to be called from an REST API. That is why I am trying to get the input value inside a variable to accomplish the task
No need to define extra var for pinCode because of you used ng-model so you can access pinCode from your controller. Also should use ng-blur instead of onBlur.
You can use like
HTML:
<input type="text" ng-model='pinCode' id="zip" ng-blur="myZipcode()">
Controller:
var myApp = angular.module('myApp' , []);
myApp.controller('myCtr', function($scope, $http){
$scope.pinCode= ''; // defaulr empty
var path = 'http://ziptasticapi.com/';
$scope. myZipcode = function() {
$http.get(path + $scope.pinCode).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;
});
};
});
You should not access html elements from your controller code. Angular's two way data-binding already transfers the form input's value into the $scope.pinCode variable. So you only need some action to trigger your server call. See this sample in the angular docs: https://docs.angularjs.org/api/ng/directive/ngSubmit
myApp.controller('myCtr', function($scope, $http) {
$scope.doCall = function() {
// $scope.pinCode() is set here
$scope.$http.get(...).then(
function(response) {
$scope.city = response.data.city; // or similar
}
);
}
});
just bind zip and pat1 on controller's scope
Controller:
myApp.controller('myCtr', function($scope, $http){
$scope.zip = document.getElementById("zip").value || 0;
$scope. pat1 = 'http://ziptasticapi.com/'+ $scope.zip || '';
$scope.myZipcode();
});
and then in zipcode
Zipcode function:
$scope.myZipcode = function myZipcode(){
$scope,zip = document.getElementById("zip").value;
$scop.pat1 = 'http://ziptasticapi.com/'+zip;
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;}
}
Complete code:
<body ng-app="myApp">
<div ng-controller="myCtr">
<form name="myForm">
<input type="text" ng-model='pinCode' id="zip" ng-blur="myZipcode">
{{city}}
{{state}}
</form>
</div>
<script>
myApp.controller('myCtr', function($scope, $http){
$scope.zip = document.getElementById("zip").value || 0;
$scope. pat1 = 'http://ziptasticapi.com/'+ $scope.zip || '';
$scope.myZipcode();
$scope.myZipcode = function myZipcode(){
$scope,zip = document.getElementById("zip").value;
$scop.pat1 = 'http://ziptasticapi.com/'+zip;
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;}
}
});
</script>
</body>
I've created a simple To Do App and while working on it I felt like I will end up placing too much code into my Controller and will eventually get messy and hard to read. I want to know how can I move my functions into factories so that my code can look somewhat cleaner.
Here is my JS:
angular.module('toDoApp', [])
.controller('toDoCtrl', function($scope){
//set $scope variables
$scope.tasks = [];
$scope.submitTask = function(){
$scope.tasks.unshift($scope.enteredTask);
$scope.enteredTask = '';
};
$scope.removeTask = function(task) {
var i = $scope.tasks.indexOf(task);
$scope.tasks.splice(i, 1);
};
})
.factory('toDoFactory', ['$http', function($http){
return function(newTask) {
};
}])
Here is the HTML if needed:
<form ng-submit="submitTask()">
<!-- task input with submit button -->
<label>Task: </label>
<input type="text" placeholder="Enter Task" ng-model="enteredTask" required>
<button>Submit</button>
</form>
<div>
<!-- create unordered list for task that are submitted
need check boxes -->
<ul>
<li ng-repeat="task in tasks">
{{ task }}
<button ng-click="removeTask()">x</button>
</li>
</ul>
</div>
As you can see I kinda started the factory but just don't know how to go about it.
Any suggestions will be greatly appreciated.
You will need to inject your factory inside controller and then use the methods defined in the factory from the controller:
angular.module('toDoApp', [])
.controller('toDoCtrl', function($scope, toDoFactory){
//set $scope variables
$scope.tasks = [];
$scope.submitTask = function(){
toDofactory.submittask(); //Just for demo.Passin your parameters based on your implementation
};
$scope.removeTask = function(task) {
var i = $scope.tasks.indexOf(task);
$scope.tasks.splice(i, 1);
};
})
.factory('toDoFactory', ['$http', function($http){
var methods = {};
methods.submittask = function(){
//your logic here
};
methods.removetask = function(){
//your logic here
}
return methods;
}])
var app = angular.module('toDoApp', []);
app.controller('toDoCtrl', function($scope, toDoFactory){
$scope.tasks = [];
toDoFactory.get = function(){
}
toDoFactory.delete = function(){
}
toDoFactory.update = function(){
}
});
app.factory('toDoFactory', ['$http', function($http){
var todo = {};
todo.get = function(){
};
todo.delete = function(){
};
todo.update = function(){
}
return todo;
}]);
This is simple architecture, you can add more logic,
Make sure you know about dependency injection(DI)
Here is the answer for those that want to see what the end result will look like when all the code is plugged in. Thanks again for the answers as it was able to guide me in the right direction.
.controller('toDoCtrl', function($scope, toDoFactory){
$scope.tasks = toDoFactory.tasks;
$scope.submitTask = function(){
toDoFactory.submitTask($scope.enteredTask);
$scope.enteredTask = '';
};
$scope.removeTask = function(task) {
toDoFactory.removeTask();
};
})
.factory('toDoFactory', ['$http', function($http){
var toDo = {
tasks: [],
enteredTask: '',
submitTask: function(task){
toDo.tasks.unshift(task);
},
removeTask: function(task) {
var i = toDo.tasks.indexOf(task);
toDo.tasks.splice(i, 1);
}
};
}])
I am in learning phase of Angularjs and am stuck in a problem for last two days. I have seen lots of answer but don't know how to adapt those solutions in my case. What I want to do is update the input field via buttons using angularjs.
// html
<body ng-controller="Controller">
<input type="number" ng-model="data" update-view>
<br>
<label for="data">{{data}}</label>
<button name="btn1" ng-click='updateInput(1)'>1</button>
</body>
// js
var app = angular.module('calculator',[]);
app.controller('Controller', function($scope, $timeout){
$scope.data = 0;
var val = '';
$scope.updateInput = function(param) {
val += String(param);
$scope.data = val;
// val = param;
// $scope.data = val;
}
});
The expressions gets evaluated but the input field is not updating. I have seen other updating views with $setViewValue and $render but I don't know how to use them here.
app.directive('updateView', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind('change', function () {
// console.log(ngModel);
scope.$apply(setAnotherValue);
});
function setAnotherValue() {
ngModel.$setViewValue(scope.data);
ngModel.$render();
}
}
};
});
Any help would be appreciated. Thanks
You don't need a directive for updating.
You seem to be setting a string value to $scope.data, which throws an error, because the input type is number.
angular.module('calculator', [])
.controller('Controller', function($scope){
$scope.data = 0;
var val = '';
$scope.updateInput = function(n){
val = n;
$scope.data = val;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<body ng-app="calculator" ng-controller="Controller">
<input type="number" ng-model="data">
<button ng-click="updateInput(1)">1</button>
</body>
I was noting that without converting the parameter into string, the input field would update with the changed model but as soon as I would change it into String, it would not update the input field. Also there was error thrown in console. So I just, on hit and trial basis, converted it back to int by changing only one piece of line $scope.data = val; into $scope.data = parseInt(val, 10); and hurrrayyy the input field is all updating just like I wanted. And as #cither suggested, I don't need to directive for this. Following is my working code
var app = angular.module('calculator',[]);
app.controller('Controller', function($scope, $timeout){
$scope.data = 0;
var val = '';
$scope.updateInput = function(param) {
val += String(param);
$scope.data = parseInt(val, 10);
}
});
when i checked checkbox am getting error in console. i have enclosed screen shot .how can i grap all slected checkbox values on submit event and how to avoid Cannot assign to read only property 'selected'error
angular
.module('test1')
.controller('Test1Controller', [
'$scope', '$http', '$location', '$window',
function($scope, $http, $location, $window) {
var storeid = window.localStorage.getItem("storeid");
$http.get('***').success(function(data, status, response)
{
$scope.items = (JSON.stringify(data[0].D_Services).replace(/\"/g, "")).split(',');
console.log($scope.items);
//console i'm getting ["Tyres", "Spares", "Accessories"]
$scope.selected = [];
});
$scope.check = function(data)
{
var arr = [];
for (var i in data) {
if (data[i].SELECTED == 'Y') {
arr.push(data[i].item);
}
}
console.log(arr);
$scope.selected = arr;
}
}
]);
<div ng-controller="Test1Controller" data-ng-init="loadservice()">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" ng-true-value="'Y'" ng-false-value="'N'"/> {{item}}
</div>
<input type="button" name="submit" value="submit" ng-click="check(items)"/>
</div>
You can achieve this by creating a modal data and append it to $scope.items
var serverData = ["Tyres", "Spares", "Accessories"]; //assuming this is server data
$scope.items = [];
for (var i = 0; i < serverData.length; i++) {
var modal = {
name: serverData[i],
selected: false
};
$scope.items.push(modal);
}
updated jsFiddle: http://jsfiddle.net/gopinathshiva/nLC3g/477/