How to get checked values from checkbox using Angular JS - javascript

Am new to angular JS. I have following check box and the data is coming from web service:
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-checked="r.value">
{{r.conditions_name}}
</label>
In console.log value is perfectly right as per my requirements. How to push value to an array i.e., arr[] and stringify it. I tried code like this..
//To fetch Medical Conditions List
$scope.parameter = "{}";
$scope.class0 = "{}";
$http.get('http://192.168.1.129:8080/apartment//member/medical/conditions/list').then(function(response) {
$scope.MedicalConditions = response.data.list;
});
$scope.$watchCollection('ids', function(newVal) {
$scope.parameter.class0 = $scope.ids;
});
$scope.alertdata = function() {
var parameter = {
"first_name": $scope.first_name,
"role": [{
"role_id": 1,
"name": "Admin",
"details": "text"
}],
"associated": [{
"associated_id": 1,
"associated_name": "Parent",
"primary_member_id": 1
}],
"class0": $scope.ids
}
parameter = JSON.stringify(parameter);

May be this will help:
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.ids = {};
$scope.arr = {};
$scope.MedicalConditions = {};
$scope.MedicalConditions[0] = {};
$scope.MedicalConditions[0].value= true;
$scope.MedicalConditions[0].conditions_name= 'first value';
$scope.MedicalConditions[1] = {};
$scope.MedicalConditions[1].value= false;
$scope.MedicalConditions[1].conditions_name= 'seconde value';
$scope.$watchCollection('ids', function(newVal) {
$scope.parameter.class0 = $scope.ids;
});
$scope.parameter = {};
$scope.parameter.firstname = 'dummy name';
$scope.parameter.class0 = $scope.ids;
});
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-checked="r.value" > {{ r.conditions_name}}
</label>
<br>
Parameter: {{parameter}}
</div>
</body>
</html>

Try like below...
var app = angular.module('exApp',[]);
app.controller('ctrl', function($scope){
$scope.ids = [];
$scope.arr = [];
$scope.checkSelected = [];
$scope.MedicalConditions = [{"conditions_name":"xxz","conditions_id":"1"}, {"conditions_name":"yyz","conditions_id":"2"}, {"conditions_name":"zzz","conditions_id":"3"}];
$scope.$watchCollection('ids', function(newVal) {
for (var i = 0; i < newVal.length; ++i) {
console.log(newVal[i]);
$scope.arr.push(newVal[i]);
}
});
$scope.checkAllR = function () {
$scope.checkAll = !$scope.checkAll;
if ($scope.checkAll) {
$scope.checkSelected = [];
angular.forEach($scope.MedicalConditions, function (checkR) {
checkR.check = $scope.checkAll;
$scope.checkSelected.push(checkR);
});
}
else {
$scope.checkSelected = [];
angular.forEach($scope.MedicalConditions, function (checkR) {
var idx = $scope.checkSelected.indexOf(checkR);
checkR.check = $scope.checkAll;
$scope.checkSelected.splice(idx, 1);
});
}
};
$scope.addChecked = function (checked) {
if ($scope.checkSelected == undefined || $scope.checkSelected == null) {
$scope.checkSelected = [];
}
var idx = $scope.checkSelected.indexOf(checked);
// delete if exists
if (idx > -1) {
$scope.checkSelected.splice(idx, 1);
checked.check = false;
}
// add
else {
$scope.checkSelected.push(checked);
checked.check = true;
}
$scope.checkAll = $scope.checkSelected.length == $scope.MedicalConditions.length ? true : false;
};
var parameter = {
"first_name": $scope.first_name,
"middle_name": $scope.middle_name,
//"class0": /*stringified data i.e., arr[] */
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp" ng-controller="ctrl">
Select All : <input type="checkbox" name="checkbox" value="1" ng-checked="checkAll" ng-click="checkAllR()"><br>
<label ng-repeat="r in MedicalConditions">
<input type="checkbox" name="checkbox" class="check-nolabel" value="1" ng-checked="r.check" ng-click="addChecked(r)"> {{ r.conditions_name}}
</label><br><br>
{{checkSelected}}
</body>

Hope this helps.
<div ng-app="myApp" ng-controller="MyCtrl">
<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]"
ng-init="ids[$index] = r.value"
type="checkbox">
{{r.condition}}
</label>
</div>
And here is your controller.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope){
$scope.ids = [];
$scope.MedicalConditions = [{
_id: 1,
value: true,
condition: 'Condition 1'
}, {
_id: 2,
value: false,
condition: 'Condition 2'
}, {
_id: 3,
value: true,
condition: 'Condition 3'
}];
});
JsFiddle

<label ng-repeat="r in MedicalConditions track by $index">
<input ng-model="ids[$index]" type="checkbox" ng-change="valCh(r)"> {{r.conditions_name}}
</label>
Controller code will look like this :
var postApp = angular.module('EntityApp', []);
postApp.controller('EntityAppCntroller', function($scope, $http, $window, $timeout, $location) {
//To fetch Medical Conditions List
$http.get('http://111.222.444:8080/apartment//member/medical/conditions/list').then(function(response) {
$scope.MedicalConditions = response.data.list;
});
var list = [];
$scope.valCh = function(value) {
list.push(value);
JSON.stringify(list);
}
$scope.alertdata = function() {
var parameter;
parameter = {
"parameter": {
"first_name": $scope.first_name,
"medicalconditions": list
}
}
$http({
url: 'http://111.222.333:8080/apartment//save/member/details',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(parameter)
}).success(function(data, status) {
if (data.status == 'success') {
alert("User Created");
$location.reload();
} else if (data.status == 'failure') {
alert("Some failure please try again later !!!");
}
});
};
});

Related

angularjs custom filter to check for values inside a data array

I have two filters which filter the data according to the queue key in the data.
Here is my code :
var app = angular.module('app', []);
app.controller('mainController', function($scope) {
// Data object
$scope.servers = [{
name: 'ServerA',
queue: '111'
},
{
name: 'Server7',
queue: '111'
},
{
name: 'Server2',
queue: '456'
},
{
name: 'ServerB',
queue: '456'
},
];
// Filter defaults
$scope.Filter = new Object();
$scope.Filter.queue = {
'PAV': '111',
'UAT': '456'
};
});
// Global search filter
app.filter('searchFilter', function($filter) {
return function(items, searchfilter) {
var isSearchFilterEmpty = true;
angular.forEach(searchfilter, function(searchstring) {
if (searchstring != null && searchstring != "") {
isSearchFilterEmpty = false;
}
});
if (!isSearchFilterEmpty) {
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item, function(term, key) {
if (term != null && !isFound) {
term = term.toString();
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if (searchstring != "" && term.indexOf(searchstring) != -1 && !isFound) {
result.push(item);
isFound = true;
}
});
}
});
});
return result;
} else {
return items;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="mainController">
<label>show 111</label>
<input type="checkbox" ng-model="Filter.queue.PAV" ng-true-value='"111"' ng-false-value='"!111"' />
<label>show 456</label>
<input type="checkbox" ng-model="Filter.queue.UAT" ng-true-value='"456"' ng-false-value='"!456"' />
<hr />
<table width="100%" cellpadding="5">
<tr>
<th>Name</th>
<th>Queue</th>
</tr>
<tr ng-repeat="server in servers | searchFilter:Filter.queue">
<td>{{server.name}}</td>
<td>{{server.queue}}</td>
</tr>
</table>
</div>
</div>
the filters work perfectly.
But if I have the data like this where the queue is inside an array:
$scope.servers = [
{name:'ServerA', queuearr:[{'queue' :'111'}]},
{name:'Server7', queuearr:[{'queue' :'111'}]},
{name:'Server2', queuearr:[{'queue' :'456'}]},
{name:'ServerB', queuearr:[{'queue' :'456'}]},
];
note : there can be multiple objects in the queuerr like
this:[{queue :'111'},{queue :'278'}]
How do I alter my current code so that the control goes inside the queuerr array and match the queue and return the result accordingly?
you have some conditions to change in the Angular.forEach take a look at the solution.
ServerB shows up in both searchs
var app = angular.module('app', []);
app.controller('mainController', function($scope) {
// Data object
$scope.servers = [{
name: 'ServerA',
queue: '111'
},
{
name: 'Server7',
queue: '111'
},
{
name: 'Server2',
queue: '456'
},
{
name: 'ServerB',
queue: '456',
queuearr: [{
queue: '456'
}, {
queue: '111'
}]
},
];
// Filter defaults
$scope.Filter = new Object();
$scope.Filter.queue = {
'PAV': '111',
'UAT': '456'
};
});
// Global search filter
app.filter('searchFilter', function($filter) {
return function(items, searchfilter) {
var isSearchFilterEmpty = true;
angular.forEach(searchfilter, function(searchstring) {
if (searchstring != null && searchstring != "") {
isSearchFilterEmpty = false;
}
});
if (!isSearchFilterEmpty) {
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item, function(term, key) {
// change here to check for arrays
if (term || Array.isArray(term) && !isFound) {
// use JSON.stringify here
term = JSON.stringify(term);
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if (searchstring != "" && term.indexOf(searchstring) != -1 && !isFound) {
result.push(item);
isFound = true;
}
});
}
});
});
return result;
} else {
return items;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="mainController">
<label>show 111</label>
<input type="checkbox" ng-model="Filter.queue.PAV" ng-true-value='"111"' ng-false-value='"!111"' />
<label>show 456</label>
<input type="checkbox" ng-model="Filter.queue.UAT" ng-true-value='"456"' ng-false-value='"!456"' />
<hr />
<table width="100%" cellpadding="5">
<tr>
<th>Name</th>
<th>Queue</th>
</tr>
<tr ng-repeat="server in servers | searchFilter:Filter.queue">
<td>{{server.name}}</td>
<td>{{server.queue}}</td>
</tr>
</table>
</div>
</div>
I think you can do it like this. It is not clear what it is exactly what you want to do because your code is overly complicated and badly aligned.
app.filter('searchFilter',function($filter) {
return function(items, searchfilter) {
const terms = Object.values(searchfilter).map(
(val)=>val.toLowerCase(),
);
return items.filter((item) =>
item.queuearr.some((q) => terms.includes(q.queue.toLowerCase())),
);
};
}
If you want to filter $scope.servers with the values of the queue you can try this. Hope this helps.
const servers = [
{name:'ServerA', queuearr:[{'queue' :'111'}]},
{name:'Server7', queuearr:[{'queue' :'111'}]},
{name:'Server2', queuearr:[{'queue' :'456'}]},
{name:'ServerB', queuearr:[{'queue' :'456'}]},
];
const itemsToCheck = { 'PAV':'111', 'UAT':'426' };
const filter = (arr, itemsToCheck) => arr.filter((item) => {
for (let v of Object.values(itemsToCheck)) {
const found = item.queuearr.find(({ queue }) => queue === v);
if (found) return true;
}
return false;
});
console.log(filter(servers, itemsToCheck));
I have modified your snippet as per your given array. Its working fine as per your need.
var app = angular.module('app', []);
app.controller('mainController', function($scope) {
// Data object
/*
$scope.servers = [{
name: 'ServerA',
queue: '111'
},
{
name: 'Server7',
queue: '111'
},
{
name: 'Server2',
queue: '456'
},
{
name: 'ServerB',
queue: '456'
},
];
*/
$scope.servers = [
{name:'ServerA', queuearr:[{'queue' :'111'}]},
{name:'Server7', queuearr:[{'queue' :'111'}]},
{name:'Server2', queuearr:[{'queue' :'456'}]},
{name:'ServerB', queuearr:[{'queue' :'456'}]},
];
// Filter defaults
$scope.Filter = new Object();
$scope.Filter.queue = {
'PAV': '111',
'UAT': '456'
};
});
// Global search filter
app.filter('searchFilter', function($filter) {
return function(items, searchfilter) {
var isSearchFilterEmpty = true;
angular.forEach(searchfilter, function(searchstring) {
if (searchstring != null && searchstring != "") {
isSearchFilterEmpty = false;
}
});
if (!isSearchFilterEmpty) {
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item.queuearr, function(term, key) {
if (term.queue != null && !isFound) {
term.queue = term.queue.toString();
term.queue = term.queue.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if (searchstring != "" &&
term.queue.indexOf(searchstring) != -1 &&
!isFound) {
result.push(item);
isFound = true;
}
});
}
});
});
return result;
} else {
return items;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="mainController">
<label>show 111</label>
<input type="checkbox" ng-model="Filter.queue.PAV" ng-true-value='"111"' ng-false-value='"!111"' />
<label>show 456</label>
<input type="checkbox" ng-model="Filter.queue.UAT" ng-true-value='"456"' ng-false-value='"!456"' />
<hr />
<table width="100%" cellpadding="5">
<tr>
<th>Name</th>
<th>Queue</th>
</tr>
<tr ng-repeat="server in servers | searchFilter:Filter.queue">
<td>{{server.name}}</td>
<td>{{server.queuearr[0].queue}}</td>
</tr>
</table>
</div>
</div>
I solved the problem by adding another forEach loop to go through the queuearr when queue is inside an array:
var app =angular.module('app', []);
app.controller('mainController', function($scope) {
// Data object
$scope.servers = [
{name:'ServerA', queuearr:[{'queue' :'111'},{'queue' :'456'}]},
{name:'Server7', queuearr:[{'queue' :'111'}]},
{name:'Server2', queuearr:[{'queue' :'456'}]},
{name:'ServerB', queuearr:[{'queue' :'456'}]},
];
// Filter defaults
$scope.Filter = new Object();
$scope.Filter.queue = {'PAV':'111',
'UAT':'456'
};
});
// Global search filter
app.filter('searchFilter',function($filter) {
return function(items,searchfilter) {
//console.log(items);
var isSearchFilterEmpty = true;
angular.forEach(searchfilter, function(searchstring) {
if(searchstring !=null && searchstring !=""){
isSearchFilterEmpty= false;
}
});
if(!isSearchFilterEmpty){
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item.queuearr, function(z) {
//console.log(item.queue);
angular.forEach(z, function(term,key) {
//console.log(z);
//console.log(item.queue);
if(term != null && !isFound){
term = term.toString();
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
//console.log(searchfilter);
searchstring = searchstring.toLowerCase();
if(searchstring !="" && term.indexOf(searchstring) !=-1 && !isFound){
result.push(item);
isFound = true;
}
});
}
});
});
});
return result;
}else{
return items;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.4/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="mainController">
<label>show 111</label>
<input type="checkbox" ng-model="Filter.queue.PAV" ng-true-value='"111"' ng-false-value='""' />
<label>show 456</label>
<input type="checkbox" ng-model="Filter.queue.UAT" ng-true-value='"456"' ng-false-value='""' />
<hr />
<table width="100%" cellpadding="5">
<tr>
<th>Name</th>
</tr>
<tr ng-repeat="server in servers | searchFilter:Filter.queue">
<td>{{server.name}}</td>
</tr>
</table>
</div>
</div>
Now it's working perfectly

modalinstance inject view model to update

I am using Modal popups to list out accounts details (accno and name). once row is selected from list view model variable(vm.vismaDebitAccount) need to update which is dynamic. In actual scenario popup will be open on textbox onclick and once row is selected from popup relevant textbox text should be update with account name. The view model variable(a particular textbox binding) should be able to inject to modalinstance result without hard cord things.
Here is my code.
my problem is why vm.vismaDebitAccount is not getting update? Please help me.
Here is the place on UI binding
<tr ng-repeat="accEntry in vm.vismaAccEntries">
<td>{{accEntry.invoiceNo}}</td>
<td><input type="text" ng-model='accEntry.debitAccNo' required name="field" ng-click="vm.openVismaAccModal('debit')" /></td>
<td><input type="text" ng-model='accEntry.debitVat' required name="field" /></td>
<td><input type="text" ng-model='accEntry.creditAccNo' required name="field" ng-click="vm.openVismaAccModal('credit')"/></td>
<td><input type="text" ng-model='accEntry.creditVat' required name="field" /></td>
<td>{{accEntry.amount}}</td>
<td>{{accEntry.voucherDate}}</td>
<td>{{accEntry.dueDate}}</td>
app.controller('invoiceCodeController', ['$routeParams', 'invoiceService', 'vismaService', '$uibModal', '$log', function ($routeParams, invoiceService, vismaService, $uibModal, $log) {
var vm = this;
var vismaDebitAccount = {
catogory: '',
account: ''
}
var vismaCreditAccount = {
catogory: '',
account: ''
}
vm.openVismaAccModal = function (accountType) {
console.log('hi before')
var modalInstance = $uibModal.open({
templateUrl: 'accountPopup.html',
controller: 'vismaAccController as vm'
});
modalInstance.result.then(function (selectedAccount) {
if (accountType === 'debit') {
vm.vismaAccEntries[0].debitAccNo = selectedAccount.account.No;
}
if (accountType === 'credit') {
vm.vismaAccEntries[0].creditAccNo = selectedAccount.account.No;
}
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}]);
app.controller('vismaAccController', ['vismaService', '$uibModalInstance', function (vismaService, $uibModalInstance) {
var vm = this;
var selectedAcc = {
category: '',
account: ''
};
Init();
function Init() {
getVismaAccData();
}
vm.tabChange = function (e) {
if (e.target.nodeName === 'A') {
e.preventDefault();
}
}
vm.rowSelect = function (index, debitAcc, flag) {
selectedAcc.category = flag;
selectedAcc.account = debitAcc;
}
vm.ok = function () {
$uibModalInstance.close(selectedAcc);
};
vm.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
function getVismaAccData() {
var errors = [];
vismaService.getSuppliers().then(function (data) {
vm.vismaSuppliers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getCustomers()
.then(function (data) {
vm.vismaCustomers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getGeneralLedger()
.then(function (data) {
vm.vismaGL = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
if (errors.length > 0) {
vm.message = errors.join(' ');
}
}
}]);

TypeError: customerFactory.getOrders is not a function

It's my third learning AngularJS and I'm struggling. I need help. I keep getting TypeError: customerFactory.getOrders is not a function I have checked for typos several times but can't find any.
customersController.js
angular.module('myApp')
.controller('CustomersController', function ($scope, $log, customerFactory, appSettings) {
'use strict';
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [];
$scope.appSettings = appSettings;
function init (){
customerFactory.getCustomers()
.success(function(customers) {
$scope.customers = customers;
})
.error(function(data, status, headers, config) {
//error handler
$log.log(data.error + ' ' + status);
});
}
init();
$scope.doSort = function (propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
});
allorders.html
<h3>Customer Orders</h3>
<br/>
Filter: <input type="text" ng-model="orderFilter.product" />
<br/><br/>
<table>
<tr>
<th>Product</th>
<th>Total</th>
</tr>
<tr ng-repeat="order in orders | filter:orderFilter | orderBy:'name'">
<td>{{ order.product }}</td>
<td>{{ order.total | currency:'PLN' }}</td>
</tr>
<tr ng-class="totalType">
<td> </td>
<td>{{ ordersTotal | currency:'PLN' }}</td>
</tr>
</table>
allOrderscontroller.js
(function() {
var AllOrdersController = function ($scope, customerFactory) {
$scope.orders = null;
$scope.ordersTotal = 0.0;
$scope.totalType;
function init() {
customerFactory.getOrders()
.success(function(orders) {
$scope.orders = orders;
getOrdersTotal();
})
.error(function(data, status, headers, config) {
//handle error
});
}
function getOrdersTotal() {
var total = 0;
for (var i = 0, len = $scope.orders.length; i < len; i++) {
total += $scope.orders[i].total;
}
$scope.ordersTotal = total;
$scope.totalType = ($scope.ordersTotal > 100) ? 'success' : 'danger';
}
init();
};
AllOrdersController.$inject = ['$scope', 'customerFactory'];
angular.module('myApp')
.controller('AllOrdersController', AllOrdersController);
}());
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.angularjs.org/1.4.5/angular.js"></script>
<script src="angular-route.js"></script>
<script src="app/controllers/app.js"></script>
<script src="app/controllers/customersController.js"></script>
<script src="app/controllers/ordersController.js"></script>
<script src="app/services/customersFactory.js"></script>
<script src="app/services/values.js"></script>
<script src="app/controllers/allOrdersController.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<ul class="nav navbar-nav">
<li>Customers</li>
<li>Orders</li>
</ul>
</nav>
</header>
<div ng-view></div>
</body>
</html>
I'm only trying to display allorders.html's content.
Console
TypeError: customerFactory.getOrders is not a function
at init (http://localhost:3000/app/controllers/allOrdersController.js:9:19)
at new AllOrdersController (http://localhost:3000/app/controllers/allOrdersController.js:28:2)
at invoke (https://code.angularjs.org/1.4.5/angular.js:4473:17)
at Object.instantiate (https://code.angularjs.org/1.4.5/angular.js:4481:27)
at https://code.angularjs.org/1.4.5/angular.js:9108:28
at link (http://localhost:3000/angular-route.js:977:26)
at invokeLinkFn (https://code.angularjs.org/1.4.5/angular.js:8746:9)
at nodeLinkFn (https://code.angularjs.org/1.4.5/angular.js:8246:11)
at compositeLinkFn (https://code.angularjs.org/1.4.5/angular.js:7637:13)
at publicLinkFn (https://code.angularjs.org/1.4.5/angular.js:7512:30) <div ng-view="" class="ng-scope">
Please help if anyone can. Almost been sitting by days for the whole day :(.
EDIT
customersFactory.js
(function() {
var customerFactory = function($http) {
var factory = {};
factory.getCustomers = function() {
return $http.get('/customers');
};
factory.getCustomer = function(customerId) {
return $http.get('/customers/' + customerId);
};
factory.getOrders = function() {
return $http.get('/orders');
}
return factory;
};
customerFactory.$inject = ['$http'];
angular.module('myApp').factory('customerFactory', customerFactory);
}());
I tried to write an orders route in server.js like so:
app.route('/orders')
.get(function(req, res)) {
var orders = [];
for (var i = 0, len = customers.length; i < len; i++) {
orders += customers[i][orders];
}
return orders;
}
})
I am trying to collect all orders from the customers array in server.js. No progress. What am I doing wrong? This is my
server.js
var express = require('express'),
app = express();
/* EXPRESS 3.0
app.configure(function () {
app.use(express.static(__dirname, '/'));
});
*/
// EXPRESS 4.0
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
// configure stuff here
app.use(express.static(__dirname + '/'));
}
/*EXPRESS 3.0
app.get('/customers/:id', function(req, res) {
var customerId = parseInt(req.params.id);
var data = {};
for (var i = 0, len = customers.length; i < len; i++) {
if (customers[i].id === customerId) {
data = customer[i];
break;
}
}
res.json(data)
});
*/
//EXPRESS 4.0
app.route('/customers/:id')
.get(function(req, res) {
var customerId = parseInt(req.params.id);
var data = {};
for (var i = 0, len = customers.length; i < len; i++) {
if (customers[i].id === customerId) {
data = customers[i];
break;
}
}
res.json(data)
})
/* EXPRESS 3.0
app.get('/customers', function(req, res) {
res.json(customers);
});
*/
//EXPRESS 4.0
app.route('/customers')
.get (function(req, res) {
return res.json(customers);
})
app.route('/orders')
.get(function(req, res)) {
var orders = [];
for (var i = 0, len = customers.length; i < len; i++) {
orders += customers[i][orders];
}
return orders;
}
})
app.listen(3000);
console.log('Express listening on port 3000');
var customers = [
{
id: 1,
joined: '2005-09-07',
name: 'Mayweather',
city: 'Brooklyn',
orderTotal: '43.1299',
orders: [
{
id: 1,
product: 'Pencils',
total: 9.9956
}
]
},
{
id: 2,
joined: '2005-09-07',
name: 'Jason',
city: 'Cleveland',
orderTotal: '89.8933',
orders: [
{
id: 1,
product: 'iPad',
total: 20.9956
}
]
},
{
id: 3,
joined: '1999-08-27',
name: 'Jade',
city: 'Wroclaw',
orderTotal: '77.0092',
orders: [
{
id: 1,
product: 'Pillows',
total: 12.2311
}
]
},
{
id: 4,
joined: '2015-09-01',
name: 'David',
city: 'Accra',
orderTotal: '13.8465',
orders: [
{
id: 1,
product: 'Serek',
total: 11.4782
}
]
},
{
id: 5,
joined: '2001-01-18',
name: 'Doyet',
city: 'Paris',
orderTotal: '23.9930',
orders: [
{
id: 1,
product: 'Serek',
total: 11.4782
}
]
}];
So, looking at your customerFactory there is no getOrders function to call yet hence why the error is triggered when making a call to this from the init function within your allOrdersController.

Having issue with angular filter in order to search through list

I am using angular filter in order to search through the list. Searching using filter is working fine but issue is along with i also have a check box('Select All') this check box is also perfoming its action fine but when i search through the list and if i get only two element out of six and then i check my 'Select box' the other four elements in rows also get checked . I want to avoid this situation . My code is below:
Html
<select-all-checkbox checkboxes="editResource.allowedUsersList" all-selected="allSelectedWtUsers" all-clear="noSelectedWtUsers" multiple="multipleWtUsers" ids="selectedWUsersIds"></select-all-checkbox>
<input type='text' ng-model="name" placeholder="search"/>
<div class="col-sm-12" ng-repeat="allowedUser in editResource.allowedUsersList | filter:{firstName:name}"></div>
Directive:
This directive is used to select checkboxes.
directive('selectAllCheckbox', function () {
return {
replace: true,
restrict: 'E',
scope: {
checkboxes: '=',
allselected: '=allSelected',
allclear: '=allClear',
multiple: '=multiple',
ids: '=ids'
},
template: '<input type="checkbox" class="input-checkbox" ng-model="master" ng-change="masterChange()">',
controller: function ($scope, $element) {
$scope.masterChange = function () {
if ($scope.master) {
angular.forEach($scope.checkboxes, function (cb, index) {
cb.isSelected = true;
});
} else {
angular.forEach($scope.checkboxes, function (cb, index) {
cb.isSelected = false;
});
}
};
$scope.$watch('checkboxes', function (newVal,oldVal) {
if(newVal !== oldVal){
var allSet = true,allClear = true,countSelected = 0;
$scope.ids = [];
angular.forEach($scope.checkboxes, function (cb, index) {
if(cb.isSelected){
countSelected ++;
$scope.ids.push(cb.id);
}
if (cb.isSelected) {
allClear = false;
} else {
allSet = false;
}
});
if(countSelected > 1){
$scope.multiple = true
}else{
$scope.multiple = false
}
if ($scope.allselected !== undefined) {
$scope.allselected = allSet;
}
if ($scope.allclear !== undefined) {
$scope.allclear = allClear;
}
$element.prop('indeterminate', false);
if (allSet) {
$scope.master = true;
} else if (allClear) {
$scope.master = false;
} else {
$scope.master = false;
$element.prop('indeterminate', true);
}
}
}, true);
}
};
});
Basically I want if i search my list of items and my item list length is 20 and i am getting 4 items using filter then my list should be of size 4 and if i clear my search box then my item list should again becomes of size 20.
Most important point is if i getting 4 items after pressing some keys into search box and if i delete 1 item and again clear my search box then i should get 19 items of my list.
Hope you understand my issue. Can anyone help me out.
I would do it with a controller (filtering the list in the controller):
http://codepen.io/jlowcs/pen/YPvvMX
HTML:
<div ng-controller="exampleCtrl">
<label><select-all-checkbox checkboxes="filteredList" all-selected="allSelectedWtUsers" all-clear="noSelectedWtUsers" multiple="multipleWtUsers" ids="selectedWUsersIds"></select-all-checkbox>select all</label>
<br>
<input type='text' ng-model="name" placeholder="search"/>
<br>
Filtered:
<div class="col-sm-12" ng-repeat="allowedUser in filteredList">
<input type="checkbox" ng-model="allowedUser.isSelected"> {{allowedUser.firstName}} {{allowedUser.lastName}}
</div>
<br>
All:
<div class="col-sm-12" ng-repeat="allowedUser in editResource.allowedUsersList">
<input type="checkbox" ng-model="allowedUser.isSelected"> {{allowedUser.firstName}} {{allowedUser.lastName}}
</div>
</div>
JS :
angular.module('exampleApp', [])
.controller('exampleCtrl', function ($scope) {
$scope.editResource = {
allowedUsersList: [
{firstName: 'Joe', lastName: 'Smith', isSelected: false},
{firstName: 'John', lastName: 'Parker', isSelected: false},
{firstName: 'Jim', lastName: 'Smith', isSelected: false}
]
};
$scope.$watch('name', function () {
$scope.filteredList = $scope.$eval('editResource.allowedUsersList | filter:{firstName:name}');
})
})
.directive('selectAllCheckbox', function () {
return {
replace: true,
restrict: 'E',
scope: {
checkboxes: '=',
allselected: '=allSelected',
allclear: '=allClear',
multiple: '=multiple',
ids: '=ids'
},
template: '<input type="checkbox" class="input-checkbox" ng-model="master" ng-change="masterChange()">',
controller: function ($scope, $element) {
$scope.masterChange = function () {
if ($scope.master) {
angular.forEach($scope.checkboxes, function (cb, index) {
cb.isSelected = true;
});
} else {
angular.forEach($scope.checkboxes, function (cb, index) {
cb.isSelected = false;
});
}
};
$scope.$watchCollection('checkboxes', function (newVal,oldVal) {
if(newVal !== oldVal){
var allSet = true,allClear = true,countSelected = 0;
$scope.ids = [];
angular.forEach($scope.checkboxes, function (cb, index) {
if(cb.isSelected){
countSelected ++;
$scope.ids.push(cb.id);
}
if (cb.isSelected) {
allClear = false;
} else {
allSet = false;
}
});
if(countSelected > 1){
$scope.multiple = true
}else{
$scope.multiple = false
}
if ($scope.allselected !== undefined) {
$scope.allselected = allSet;
}
if ($scope.allclear !== undefined) {
$scope.allclear = allClear;
}
$element.prop('indeterminate', false);
if (allSet) {
$scope.master = true;
} else if (allClear) {
$scope.master = false;
} else {
$scope.master = false;
$element.prop('indeterminate', true);
}
}
}, true);
}
};
});
angular.bootstrap(document, ['exampleApp']);

ngClick not firing in nested ngRepeat filled with data from $http.post()

I have an AngularJS app to search for journeys. In the part of the problem I am trying to show all available countries per region. The idea is that when you click a country, a function has to be executed. But it never fires...
Any help?
View
<div id="headersearch" ng-controller="ProductSearchController">
<div id="headersearchContainer">
<input id="tripchoise" class="field" type="text" placeholder="Hoe ver wil je gaan?" ng-model="country" ng-change="switchView('countries')" ng-blur="switchView('')" ng-focus="switchView('countries')" />
<div id="triptypechoise">
<div class="triptype" ng-class="{active: filter=='single'}" title="Singlereizen" ng-click="switchFilter('single')"><img src="/Resources/Images/Layout/singlereis.png" alt="Singlereizen" /></div>
<div class="triptype" ng-class="{active: filter=='custom'}" title="Maatwerkreizen" ng-click="switchFilter('custom')"><img src="/Resources/Images/Layout/maatwerk.png" alt="Maatwerkreizen" /></div>
<div class="triptype" ng-class="{active: filter=='group'}" title="Groepsreizen" ng-click="switchFilter('group')"><img src="/Resources/Images/Layout/groepsreis.png" alt="Groepsreizen" /></div>
</div>
<div id="tripdeparturedatechoise" class="field arrow">
{{date}}
</div>
</div>
<div id="headersearchButton">
<span>ZOEK</span>
</div>
<div class="clear"></div>
<input type="text" class="datepicker datehide" id="searchdepartureDate" ng-model="date" datepicker/>
<div id="searchList" ng-class="{hide:view==''}">
<div class="loadingproducts" data-ng-show="loading">Loading products...</div>
<article class="searchentry" ng-show="view=='countries'">
<div class="" ng-repeat="region in regions">
<p>{{region.Name}}</p>
<ul>
<li ng-repeat="country in region.Countries">
<a ng-click="test()">{{country.Name}}</a>
</li>
</ul>
</div>
</article>
</div>
</div>
CONTROLLER
SearchApp.controller("ProductSearchController", function ($scope, $http) {
$scope.date = "Vertrek";
$scope.filter = "single";
$scope.view = "";
$scope.country = "";
$scope.switchFilter = function (filter) {
if ($scope.filter != filter) {
$scope.filter = filter;
$scope.search();
}
}
$scope.switchView = function (view) {
if ($scope.view != view)
$scope.view = view;
if ($scope.view != "" && $scope.view != "countries")
$scope.search();
}
$http.post("/AVProductList/GetCountriesByRegionAsync")
.success(function (response) {
$scope.regions = response.regions;
});
$scope.search = function () {
$scope.loading = true;
$http.post("/AVProductList/SearchProductsHeader?view="+ $scope.view +"&filter=" + $scope.filter, { SearchParameters: {Country: $scope.country}})
.success(function (data) {
if ($scope.filter == "custom")
$scope.trips = data.results;
else {
if ($scope.view == "trips")
$scope.trips = data.grouped.RoundtripgroupCode.doclist.docs;
else if ($scope.view == "departures")
$scope.trips = data.response.docs;
}
});
};
$scope.changeDate = function () {
if (isValidDate($scope.date)) {
$scope.view = "departures";
$scope.search();
}
else {
$scope.date = "Vertrek";
$scope.view = "trips";
}
}
$scope.selectCountry = function (name, code) {
$scope.countrycode = code;
$scope.country = name;
$scope.view = isValidDate($scope.date) ? "departures" : "trips";
$scope.search();
}
$scope.test = function () {
alert("Hoi");
}
});
Json result example of
$http.post("/AVProductList/GetCountriesByRegionAsync")
.success(function (response) {
$scope.regions = response.regions;
});
{
regions:[
{
Name:"Asia",
Countries:
[
{
Name: "China",
Code: "CH"
}
,...
]
}
,...
]
}
I made a stupid mistake:
The ngBlur on "tripchoise" was fired before the ngClick.

Categories