HTML Code
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>
document.write("<base href=\"" + document.location + "\" />");
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1> NG options</h1>
<form name="addUser">
Application:
<select ng-model="filterAddUser.application" ng-init ="filterAddUser.application = 'STACK'" title="" ng-options="value as value for (key , value) in applicationStatus">
</select>
Roles:
<select ng-model="filterAddUser.role" title="" ng-init ="filterAddUser.role = 'R'" ng-options="role.value as role.param for role in roleStatus">
</select>
<button ng-click="addToCart()">AddItem</button>
<div class="addCart">
<ul ng-repeat="item in items">
<li><b>Application:</b> {{item.application}}</li>
<li><b>Role:</b> {{item.role}}</li>
<li class="actionOptions">
<button ng-click="toggleSelected($index)">removeItem</button>
</li>
</ul>
</div>
</form>
</body>
</html>
Javascript Code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.addToCart = function() {
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = "";
$scope.filterAddUser['role'] = "";
}
$scope.toggleSelected = function(index) {
$scope.items.splice(index, 1);
};
});
All that i am trying to do is when i add the application to the cart that application needs to be removed from the dropdwon and also when i click on the remove item that needs to be pushed back to the cart i have included a plunker as well http://plnkr.co/edit/kSsetX?p=preview
need help on the same.
Updated your plunkr: http://plnkr.co/edit/QQobh7Jx76r7lDzw7TzV
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
var deletedApplication = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.filterAddUser = {
application: $scope.applicationStatus[0],
role: $scope.roleStatus[0]
};
$scope.addToCart = function() {
deletedApplication.push([
$scope.filterAddUser.application, $scope.applicationStatus[$scope.filterAddUser.application]
]);
delete $scope.applicationStatus[$scope.filterAddUser.application];
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = $scope.applicationStatus[0];
$scope.filterAddUser['role'] = $scope.roleStatus[0];
}
$scope.toggleSelected = function(index) {
var addApp = deletedApplication.filter(function(deletedApp){
return deletedApp[0] === $scope.items[index].application;
})[0];
$scope.applicationStatus[addApp[0]] = addApp[1];
console.log($scope.applicationStatus);
$scope.items.splice(index, 1);
};
});
Related
I am facing some issue while returning value from angular forEach.
Here is my data:
vm.memberDetails={
"member": [
{
"firstName": "HARRY UTTWO",
"lastName": "POTTER",
}
],
"User": [
{
"memberId": 7586671,
"customerId": 7586671,
"customerStatus": "T",
"firstName": "HEMOOINE",
"lastName": "POTTER",
},
]
}
vm.mockData = {
"data": [{
"memberNo": 7586671,
"suffix": "A"
}]
}
Here I need to compare memberId and get name from first data.I used angular.forEach but for name i need to use
vm.memberDetails.User[0].firstName but it return only on value with looping.
Controller:
angular.forEach(vm.memberDetails.User, function (value1,key1) {
angular.forEach(vm.mockData, function (value2,key2) {
if (value1.memberId === value2.memberNo) {
vm.some= vm.memberDetails.User[0].firstName;
}
});
});
return vm.some;
Any help would be appreciated.
Thanks.
It looks like you need to grab the data array from vm.mockData so change the line angular.forEach(vm.mockData, function (value2,key2) { into angular.forEach(vm.mockData.data, function (value2,key2) {
angular.forEach(vm.memberDetails.User, function (value1,key1) {
angular.forEach(vm.mockData.data, function (value2,key2) {
if (value1.memberId === value2.memberNo) {
vm.some= vm.memberDetails.User[0].firstName;
}
});
});
return vm.some;
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
</head>
<body ng-controller="mCon">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.7/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('mCon', function(){
var vm = this;
vm.memberDetails = {
"member": [{
"firstName": "HARRY UTTWO",
"lastName": "POTTER",
}],
"User": [{
"memberId": 7586671,
"customerId": 7586671,
"customerStatus": "T",
"firstName": "HEMOOINE",
"lastName": "POTTER",
}, ]
}
vm.mockData = {
"data": [{
"memberNo": 7586671,
"suffix": "A",
}
]
}
angular.forEach(vm.memberDetails.User, function (value1,key1) {
angular.forEach(vm.mockData.data, function (value2,key2) {
if (value1.memberId === value2.memberNo) {
vm.some= vm.memberDetails.User[0].firstName;
}
});
});
return vm.some;
})
</script>
</body>
</html>
could you please tell me how to sort list in angular 1 on button click ? On button click I want to toggle (ascending and descending )sort list.
https://plnkr.co/edit/HYuk7DAgOY6baWhrvXko?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
vm =this;
$scope.name = 'World';
$scope.sortDir = "ASC"
$scope.customerData= [
{
"name":"naveen",
"Location":"Delhi",
"email":"naveen.nsit89#gmail.com"
},
{
"name":"sss",
"Location":"Delhi",
"email":"naveen.nsit89#gmail.com"
},
{
"name":"aa",
"Location":"Delhi",
"email":"naveen.nsit89#gmail.com"
},
{
"name":"zzz",
"Location":"Delhi",
"email":"naveen.nsit89#gmail.com"
}
]
$scope.sortButtonClick =function(){
$scope.sortDir = "DESC"
}
});
You can do this using a filter orderBy,
$scope.sortButtonClick = function() {
if($scope.sortDir === "ASC"){
$scope.sortDir = "DESC"
$scope.customerData = $filter('orderBy')($scope.customerData, '-name');
}else{
$scope.sortDir = "ASC"
$scope.customerData = $filter('orderBy')($scope.customerData, 'name');
}
}
DEMO
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $filter) {
vm = this;
$scope.name = 'World';
$scope.sortDir = "ASC"
$scope.customerData = [{
"name": "naveen",
"Location": "Delhi",
"email": "naveen.nsit89#gmail.com"
}, {
"name": "sss",
"Location": "Delhi",
"email": "naveen.nsit89#gmail.com"
}, {
"name": "aa",
"Location": "Delhi",
"email": "naveen.nsit89#gmail.com"
}, {
"name": "zzz",
"Location": "Delhi",
"email": "naveen.nsit89#gmail.com"
}]
$scope.sortButtonClick = function() {
if($scope.sortDir === "ASC"){
$scope.sortDir = "DESC"
$scope.customerData = $filter('orderBy')($scope.customerData, '-name');
}else{
$scope.sortDir = "ASC"
$scope.customerData = $filter('orderBy')($scope.customerData, 'name');
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="sortButtonClick()">{{sortDir}}</button>
<ul style="margin: 40px;">
<li ng-repeat="item in customerData ">
<span>{{item.name}}</span>
<button ng-click="deleteItem(item)">X</button>
</li>
</ul>
</body>
</html>
HTML
<li ng-repeat="item in customerData | orderBy:propertyName:reverse">
<span>{{item.name}}</span>
<button ng-click="deleteItem(item)">X</button>
</li>
Controller
$scope.propertyName = 'name';
$scope.reverse = true;
$scope.sortButtonClick =function(){
$scope.reverse = !$scope.reverse
}
Demo
I am a new bie to angular and trying to learn it.
I am trying to display user data from a webservice that I received as response.
here's the response
{
"Users": {
"SearchTerm": "angularjs ra1",
"ResultsPerPage": "20",
"RecordStartNumber": "0",
"TotalEstimatedResults": "6",
"User": [{
"WWID": "123456",
"Email": "mary.p.wilson#yahoo.com",
"BusinessTitle": "Project Manager",
"Name": "Mary Wilson",
"firstname": "Mary",
"lastname": "Wilson",
"idsid": "RAP"
}, {
"WWID": "1234567",
"Email": "steve.r.smith#gmail.com",
"BusinessTitle": "Quality Assurance",
"Name": "Steve Smith",
"firstname": "Steve",
"lastname": "Smith",
"idsid": "DRPRESTO"
}, {
"WWID": "12345678",
"Email": "jon.jones#gmail.com",
"BusinessTitle": "Chef",
"Name": "Jon Jones",
"firstname": "Jon",
"lastname": "Jones",
"idsid": "JJONES"
}]
}
}
MyScript.js
var Application = angular.module('TestModule', []);
Application.controller('TestController', function ($scope,$http) {
$scope.TestValue = "Hello World from Controller";
$scope.Myfunc = function asdf() {
$http.get('http://unifiedcollaborationprofile.gots.com/search/expert/data/v2/?apiKey=SECRET&listFromPersonNumber=0&numPeoplePerPage=20&query=angularjs+ra1&returnFriendlyResults=true').then(
function (response) {
$scope.users = [];
angular.forEach(response.Users, function (value, key) {
$scope.users.push(value);
});
});
};
});
Page.html
<!DOCTYPE html>
<html ng-app="TestModule">
<head>
<title></title>
<meta charset="utf-8" />
</head>
{{2+3}}
<body>
<div ng-controller="TestController">
{{2+3}}
{{TestValue}}
<input type="text" ng-model="TestValue" />
<input type="button" value="Click Me To Get All Users!!!!" ng-click="Myfunc()" />
<ul ng-repeat="k in users">
<li>WWID:{{k.WWID}} Email:{{k.Email}} Name:{{k.Name}} IDSID:{{k.idsid}}</li>
</ul>
</div>
</body>
</html>
<script src="scripts/angular.min.js"></script>
<script src="scripts/MyScripts/MyScript.js"></script>
But nothing gets rendered on my Page.
I am not sure if I am rightly accessing the nested User object in Users Collection of JSON and its properties.
what am I missing.
I've created plunker with your code and all I did to make it work is to change it to this:
$scope.Myfunc = function asdf() {
$http.get('test.json').then(function(response) {
$scope.users = [];
angular.forEach(response.data.Users.User, function(value, key) {
$scope.users.push(value);
});
});
};
http://plnkr.co/edit/Fu1tCnhxSn9dgBXtTJ9r?p=preview
You must remember that then after http promise gets resolved receives an object that contains several values: status code, headers and data that will contain your data
I think problem is here
$scope.users = [];
angular.forEach(response.Users, function (value, key) {
$scope.users.push(value);
});
try change to
$scope.users = response.data.Users
or you can change to
$scope.users = [];
angular.forEach(response.data.Users, function (value, key) {
$scope.users.push(value);
});
angular.forEach(response.Users.User, function (value, key) {
$scope.users.push(value);
});
your array is nested so you have to call the array in the object
I am using angular's ng-options to populate the html with the names of people. I want it to pre-select the value that I have set as the ng-model (registrantSelected). But for some reason, it won't do so.
I have looked up various different documentations for ng-options and looked at a bunch of other stack overflow posts about ng-options, but I can't seem to figure out what I am doing wrong.
Code can be found in this plunker or below:
Javascript:
angular.module('app', [])
.controller("MainController", ["$scope", function($scope) {
$scope.paidDuesCompanyPeople = [{
"FirstName": "Person",
"LastName": "One",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
}, {
"FirstName": "Second",
"LastName": "Person",
"MemberType": {
"IsMember": true,
"Name": "Member"
}
}, {
"FirstName": "Three",
"LastName": "People",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
}];
$scope.registrantSelected = {
"FirstName": "Person",
"LastName": "One",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
};
}]);
HTML:
<div ng-app="app" ng-controller="MainController">
<div class="col-xs-12 col-sm-5">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-6 control-label">Registration for</label>
<div class="col-sm-6">
<select class="form-control" ng-model="registrantSelected" ng-options="person.FirstName + ' ' + person.LastName for person in paidDuesCompanyPeople">
</select>
</div>
</div>
</form>
</div>
{{registrantSelected}}
</div>
Thank you for any help you can give!
You could do this thing by introducing track by in your ng-options but for having track by you should have unique property over there. I'd highly recommnd you to add Id property so that would make each record unique & you can track by the same. But for now just for demonstration you can track it by person.FirstName + person.Lastname(you will have track by person.Id when you add id)
<select class="form-control"
ng-model="registrantSelected"
ng-options="person.FirstName + ' ' + person.LastName for person in paidDuesCompanyPeople track by person.FirstName + person.Lastname ">
</select>
Demo Here
You should be able to set it in the controller, like so...
$scope.registrantSelected = $scope.paidDuesCompanyPeople[0];
Which makes your controller look like this (drop it in your plunkr)
Edit: I have added a plunkr as requested http://plnkr.co/edit/r8XAWqBheAATwc8zXGSY?p=preview
angular.module('app', [])
.controller("MainController", ["$scope", function($scope) {
$scope.paidDuesCompanyPeople = [{
"FirstName": "Person",
"LastName": "One",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
},{
"FirstName": "Second",
"LastName": "Person",
"MemberType": {
"IsMember": true,
"Name": "Member"
}
},{
"FirstName": "Three",
"LastName": "People",
"MemberType": {
"IsMember": false,
"Name": "Non-member"
}
}];
$scope.registrantSelected = $scope.paidDuesCompanyPeople[0];
}]);
if you want to do it in the view,
<select ng-model="registrantSelected"
ng-options="person.FirstName + ' ' + person.LastName for person in paidDuesCompanyPeople"
ng-init="registrantSelected=paidDuesCompanyPeople[0]"></select>
change registrantSelected value to this:
$scope.registrantSelected = $scope.paidDuesCompanyPeople[0];
in javascript every two objects are the same only if both of them are referring to same object:
var x1 = { id : 1 };
var x2 = { id : 1 };
console.log(x1 == x2); // false
var y1 = { id : 1 };
var y2 = y1;
console.log(y1 == y2); // true
I have a view model containg an object that is used to display some checkboxes:
components = {
"ComponentInfos": [
{
"Id": "1abb0ee5-7e44-4e45-92da-150079066e99",
"FriendlyName": "Component1",
"LimitInfos": [
{
"Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c",
"FriendlyName": "Component1 Full",
},
{
"Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2",
"FriendlyName": "Component1 Light",
}
]
}
I am able to create the checkboxes with FriendlyName as label:
<h4>{{l.FriendlyName}}</h4>
<div>
<div ng-repeat="limitinfo in l.LimitInfos">
<label>
<input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]"
value="{{limitinfo.Id}}"/> {{limitinfo.FriendlyName}}
</label>
</div>
</div>
I want to store the selected LimitInfo.Id in an array for each selected checkbox. I was able to store them in an object like this:
settings = {
"ComponentInfos" : {}
};
Result example:
"2e80bedb-4a18-4cc4-bdfd-837ffa130947": true,
"add1edf8-4f11-4178-9c78-d591a6f590e3": true
What I do need is to store the LimitInfo.Idin an array like this:
settings = {
"ComponentInfos" : []
};
Expected result:
"2e80bedb-4a18-4cc4-bdfd-837ffa130947", "add1edf8-4f11-4178-9c78-d591a6f590e3"
I uploaded my code to Plunker.
you can use a ng-click method on the checkbox with a custom controller method to push to that array.
<input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]"
value="{{limitinfo.Id}}" ng-click="toggleSelection(limitinfo.ImpliedLimits)"/>
$scope.toggleSelection = function toggleSelection(item) {
var idx = $scope.vm.settings.ComponentInfos.indexOf(item);
if (idx > -1) {
$scope.vm.settings.ComponentInfos.splice(idx, 1);
}
else {
$scope.vm.settings.ComponentInfos.push(item[0]);
}
};
see this plnkr.
see this answer
One line solution
You can do the following in vanilla JS (ES5 and above, so modern browsers)
var data = {
"a": true,
"b": false,
"c": true,
"d": false,
"e": true,
"f": true
}
var arr = Object.keys(data).filter( key => !!data[key] );
// ['a', 'c', 'e', 'f']
Demo by directive:
var app = angular.module('plunker', []);
app.directive('myCheckbox',function(){
return {
restrict:'EA',
template:'<label>'
+'<input type="checkbox" ng-model="model" ng-change="toggleModel()" /> {{label}}'
+'</label>',
replace: true,
scope:{
label:'#',
value:'#',
output:'='
},
link:function(scope,elements,attrs){
//init checked status
scope.model=scope.output.indexOf(scope.value) > -1;
//binding click replace watch model
scope.toggleModel = function(){
if(scope.model){
scope.output.push(scope.value);
return false;
}
scope.output.splice(scope.output.indexOf(scope.value),1);
}
}
}
});
function MyViewModel()
{
this.components = {
"ComponentInfos": [
{
"Id": "1abb0ee5-7e44-4e45-92da-150079066e99",
"FriendlyName": "Component1",
"LimitInfos": [
{
"Id": "4b7cd37a-2378-4f4f-921b-e0375d60d19c",
"FriendlyName": "Component1 Full",
"ImpliedLimits": [
"ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2"
]
},
{
"Id": "ff9ebe78-fbe4-4a26-a3df-6ec8e52cd0f2",
"FriendlyName": "Component1 Light",
"ImpliedLimits": [
"4f74abce-5da5-4740-bf89-dc47dafe6c5f"
]
},
{
"Id": "4f74abce-5da5-4740-bf89-dc47dafe6c5f",
"FriendlyName": "Component2 User",
"ImpliedLimits": []
}
]
},
{
"Id": "ad95e191-26ee-447a-866a-920695bb3ab6",
"FriendlyName": "Component2",
"LimitInfos": [
{
"Id": "8d13765a-978e-4d12-a1aa-24a1dda2149b",
"FriendlyName": "Component2 Full",
"ImpliedLimits": [
"4f74abce-5da5-4740-bf89-dc47dafe6c5f"
]
},
{
"Id": "2e80bedb-4a18-4cc4-bdfd-837ffa130947",
"FriendlyName": "Component2 Light",
"ImpliedLimits": [
"4f74abce-5da5-4740-bf89-dc47dafe6c5f"
]
},
{
"Id": "add1edf8-4f11-4178-9c78-d591a6f590e3",
"FriendlyName": "Component2 Viewer",
"ImpliedLimits": [
"4f74abce-5da5-4740-bf89-dc47dafe6c5f"
]
}
]
}
]
};
this.settings = {
"ComponentInfos" : ["4b7cd37a-2378-4f4f-921b-e0375d60d19c","2e80bedb-4a18-4cc4-bdfd-837ffa130947"]
};
}
app.controller('MainCtrl', function($scope) {
$scope.vm = new MyViewModel();
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="l in vm.components.ComponentInfos">
<h4>{{l.FriendlyName}}</h4>
<div>
<div ng-repeat="limitinfo in l.LimitInfos">
<my-checkbox label="{{limitinfo.FriendlyName}}" value="{{limitinfo.Id}}" output="vm.settings.ComponentInfos"></my-checkbox>
</div>
</div>
</div>
<hr>
<pre>
{{vm.settings | json }}
</pre>
</body>
</html>
You can use the ng-click and make an update of your list.
I've added this to your MyViewModel function and changed the type of your ComponentInfosto an array.
this.update = function (value) {
var exists = false;
for (var elem of this.settings["ComponentInfos"]){
if (elem === value) {
exists = true;
}
}
if(exists) {
var index = this.settings["ComponentInfos"].indexOf(value);
this.settings["ComponentInfos"].splice(index,1);
} else {
this.settings["ComponentInfos"].push(value);
}
}
Additionally you need to change the input in the html to
<input type="checkbox" ng-click="vm.update(limitinfo.Id)"/> {{limitinfo.FriendlyName}}
I am new to angularJS, Try this :
Add this snippet to app.js
this.data =[];
this.selection = function(){
this.data =[];
angular.forEach(this.settings["ComponentInfos"], function(value, key) {
if(value)
this.push(key);
}, this.data);
}
This to body of index.html
<div ng-repeat="l in vm.components.ComponentInfos">
<h4>{{l.FriendlyName}}</h4>
<div>
<div ng-repeat="limitinfo in l.LimitInfos">
<label>
<input type="checkbox" ng-model="vm.settings.ComponentInfos[limitinfo.Id]" ng-click="vm.selection()"
value="{{limitinfo.Id}}"/> {{limitinfo.FriendlyName}}
</label>
</div>
</div>
</div>
<hr>
<pre>
{{vm.settings | json }}
{{vm.data}}
</pre>