How to get a variable from Object as ng-model using angular - angularjs

I am using ng-repeat for list of options.In that list I have ID and DESCRIPCION,when select one option am appending ID and DESCRIPCION to ng-model like as Object.In controller part need to ceperate ID and DESCRIPCION.I used below code but getting undefined in alert when select one option.
http://jsfiddle.net/KN9xx/1237/
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css" rel="stylesheet" />
<div ng-app="myapp" ng-controller="FirstCtrl">
<select class="form-control selectpicker" data-live-search="true" ng-model="subappData" ng-change="getSubApplicationDetails(subappData)" id="subapplicationid" style="height: 21px;width: 300px;-moz-margin-start: 132px;margin-left: 138px;margin-top: 2px;-moz-margun-start: 132px;">
<option value="">Select</option>
<option ng-repeat='subapp in subapplicationList | filter:query' data-select-watcher data-last="{{$last}}" value = "{{subapp}}"> {{subapp.ID}} - {{subapp.DESCRIPCION}} </option>
</select>
</div>
controller.js:
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.subapplicationList = [
{"ID" : 9 ,"DESCRIPCION" : "a" },
{"ID" : 1 ,"DESCRIPCION" : "b" },
{"ID" : 2 ,"DESCRIPCION" : "c" },
{"ID" : 3 ,"DESCRIPCION" : "d" },
{"ID" : 4 ,"DESCRIPCION" : "e" },
{"ID" : 5 ,"DESCRIPCION" : "f" },
{"ID" : 6 ,"DESCRIPCION" : "g" },
{"ID" : 7 ,"DESCRIPCION" : "h" },
{"ID" : 8 ,"DESCRIPCION" : "i" }
];
$scope.getSubApplicationDetails = function(subappData) {
alert(JSON.stringify(subappData));
};
});
myapp.directive('selectWatcher', function ($timeout) {
return {
link: function (scope, element, attr) {
var last = attr.last;
if (last === "true") {
$timeout(function () {
$(element).parent().selectpicker('val', 1);
$(element).parent().selectpicker('refresh');
});
}
}
};
});

Try like this
$scope.getSubApplicationDetails = function(subappData) {
var object = JSON.parse(subappData)
console.log(object.ID);
};

Related

Angular js select specific data from json using date or filter it by date

I am new to angular js , how to select specific or certain data from json array.Return data from an array which date is equal to today , and also get data from json of this current week(all data of the current week), and also of the data of this current month. Thanks
$scope.Combination = [
{
"Name" : "HelloWorld",
"Type" : "Phyton",
"Date": "01/11/2018"
},
{
"Name" : "HelloWorld",
"Type" : "C#",
"Date": "01/08/2018"
},
{
"Name" : "HelloWorld",
"Type" : "JS",
"Date": "01/04/2018"
},
{
"Name" : "HelloWorld",
"Type" : "Ruby",
"Date": "01/07/2018"
},
{
"Name" : "HelloWorld",
"Type" : "C",
"Date": "01/010/2018"
}
];
<!DOCTYPE html>
<html ng-app="ToDo">
<head>
<title>Create Angularjs To Do Application with demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-controller="todoController">
<ul>
<li ng-repeat="todo in combinations|getCombinations ">
{{todo.Date}}
</li>
</ul>
{{name}}
</div>
<script>
var app = angular.module('ToDo',[])
app.controller('todoController',['$scope', function($scope){
$scope.combinations = [
{
"Name" : "HelloWorld",
"Type" : "Phyton",
"Date": "01/11/2018"
},
{
"Name" : "HelloWorld",
"Type" : "C#",
"Date": "01/08/2018"
},
{
"Name" : "HelloWorld",
"Type" : "JS",
"Date": "01/04/2018"
},
{
"Name" : "HelloWorld",
"Type" : "Ruby",
"Date": "01/07/2018"
},
{
"Name" : "HelloWorld",
"Type" : "C",
"Date": "01/10/2018"
}
];
}]);
angular.module('ToDo').filter('getCombinations', function($filter) {
return function (combinations) {
var month_filtered_list = [];
for (var i = 0; i < combinations.length; i++) {
var thirty_days_ago = new Date().getTime() - 30*24*60*60*1000;
var com_date = new Date(combinations[i]["Date"]).getTime();
if (com_date >= thirty_days_ago) {
month_filtered_list.push(combinations[i]);
}
}
return month_filtered_list;
}
});
</script>
</body>
</html>
Here you can use filter to show combination:
For monthly combination:
angular.module('ToDo').filter('getCombinations', function($filter) {
return function (combinations) {
var month_filtered_list = [];
for (var i = 0; i < combinations.length; i++) {
var thirty_days_ago = new Date().getTime() - 30*24*60*60*1000;
var com_date = new Date(combinations[i]["Date"]).getTime();
if (com_date >= thirty_days_ago) {
month_filtered_list.push(combinations[i]);
}
}
return month_filtered_list;
}
});
DOM looks like this
<tr ng-repeat="order in combinations|getCombinations">
Similarly you can do for the weak also by just changing the
var thirty_days_ago = new Date().getTime() - 30*24*60*60*1000;
to
var seven_days_ago = new Date().getTime() - 7*24*60*60*1000;
for present day:
.filter('getTodayCombinations', function() {
return function (combinations) {
var today_filtered_list = [];
for (var i = 0; i < combinations.length; i++) {
var com_date = new Date(combinations[i].Date).getTime();
if (com_date == new Date().getTime()) {
today_filtered_list.push(combinations[i]);
}
}
return month_filtered_list;
}
});

AngularJS | how to orderBy with a multidimensional Object?

I want to get my ng-repeat to be ordered by rank, how would I write the expression?
<div ng-app="myApp" ng-controller="orderCtrl">
<ul>
<li ng-repeat="(key, value) in cars | orderBy: cars[key].rank ">
{{cars[key].longName}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.cars = {
"BTC" : {
"longName" : "Bitcoin",
"rank" : 1
},
"BCH" : {
"longName" : "Bitcoin Cash",
"rank" : 3
},
"ETH" : {
"longName" : "Ethereum",
"rank" : 2
},
"ETC" : {
"longName" : "Ethereum Classic",
"rank" : 15
},
"IOTA" : {
"longName" : "IOTA",
"rank" : 4
},
"XRP" : {
"longName" : "Ripple",
"rank" : 6
},
"XVG" : {
"longName" : "Verge",
"rank" : 5
}
};
});
</script>
Order by can only be applied to arrays and not objects. You must convert your object to an array or create your own filter : https://justinklemm.com/angularjs-filter-ordering-objects-ngrepeat/

Meteor: How to structure Mongo data from Google Sheets

The BSON data list contains very unneeded values as shown below. The problem am I having is returning an array subset from Mongo so that I could display it in a template using Meteor.
Mongo stores the data as such:
meteor:PRIMARY> db.ga_spreadsheet.find().pretty()
{
"_id" : "7YLifh9C6Gp8HPCTm",
"spreadsheet" : "NBATEST",
"header" : null,
"cells" : {
"1" : {
"1" : {
"row" : "1",
"col" : "1",
"value" : "name"
},
"2" : {
"row" : "1",
"col" : "2",
"value" : "position"
},
"3" : {
"row" : "1",
"col" : "3",
"value" : "salary"
& client/view.js does the pull request
GASpreadsheet = new Mongo.Collection('GASpreadsheet');
if (Meteor.isClient) {
Meteor.call("spreadsheet/fetch","1kdRtyhrvXN1aEf35NwtA8pzHfjc9-lNwV76CE_Zr_g");
spreadsheetData = GASpreadsheet.findOne({spreadsheet: 'NBATEST'})
Template.nba.helpers({
'player': function(){
var currentUserId = Meteor.userId();
return GASpreadsheet.find({ createdBy: currentUserId },
{ sort: {score: -1, name: 1} });
},
cellState: function(x, y) {
if(screenArray[x][y] === 1){
return 'live';
}
else {
return 'dead';
}
},
'selectedClass': function(){
var playerId = this._id;
var selectedPlayer = Session.get('selectedPlayer');
if(playerId == selectedPlayer){
return "selected"
}
},
'selectedPlayer': function(){
var selectedPlayer = Session.get('selectedPlayer');
return GASpreadsheet.findOne({ _id: selectedPlayer });
}
});
}
view/main.html
<template name="nba">
<div class="gridWrapper">
{{#each row in rows}}
<div class="row">
{{#let rowIndex=#index}}
{{#each cell in row}}
<div class="cell {{cellState rowIndex #index}}">{{this}}</div>
{{/each}}
{{/let}}
</div>
{{/each}}
</div>
</template>

how to get selected node value for treeview using click event in angularjs directives

i am using directive concept in angularjs to display selected node value for tree view using click event function in angularjs.below is my sample code
Tree.html:
<div
data-angular-treeview="true"
data-tree-model="roleList"
data-node-id="roleId"
data-node-label="roleName"
data-node-children="children"
data-ng-click="selectNode(roleList[1])"
data-node-children="children">
</div>
treeviewcontroller.js:
$scope.roleList1 = [
{ "roleName" : "User", "roleId" : "role1", "children" : [
{ "roleName" : "subUser1", "roleId" : "role11", "children" : [] },
{ "roleName" : "subUser2", "roleId" : "role12", "children" : [
{ "roleName" : "subUser2-1", "roleId" : "role121", "children" : [
{ "roleName" : "subUser2-1-1", "roleId" : "role1211", "children" : [] },
{ "roleName" : "subUser2-1-2", "roleId" : "role1212", "children" : [] }
]}
]}
]},
{ "roleName" : "Admin", "roleId" : "role2", "children" : [] },
{ "roleName" : "Guest", "roleId" : "role3", "children" : [] }
];
Treeview.js:
scope.selectNode = function(val)
{
alert(val.roleName);
}
output:
user
subuser1
subuser1-1
Admin
subadmin1
from this output in alert place 'Admin' will be dispalyed by click on Admin node.but i want to display dynamically selected node value in click event function.please suggest me how to do this.
Thanks
In order to dynamically select node of the tree I did following:
Let's say you want to select first (top, [0]) element of your tree.
so first add data-tree-id="myTreeId" to your HTML:
<div
data-angular-treeview="true"
data-tree-model="roleList"
data-node-id="roleId"
data-node-label="roleName"
data-node-children="children"
data-ng-click="selectNode(roleList[1])"
data-node-children="children"
data-tree-id="myTreeId">
</div>
than in Controller:
$scope.roleList1[0].selected = "selected";
$scope.myTreeId.currentNode = $scope.roleList1[0];
In Tree.html :
Add line :
data-tree-id="mytree"
Modify data-ng-click event :
data-ng-click="selectNode(mytree.currentNode.roleName)"
In Treeview.js :
scope.selectNode = function(val) { alert(val); }

Dynamic form with parent child combos

I am very new to AngularJS and after watching some pluralsight videos I decided to build a simple web page using it.
The page should initially load with one select box which is populated by an ajax request (this contains all of the data). Then, based on the value selected, a new select element may need to be created containing the child data. This will continue to happen until an option is selected that has no child ids. The format of data I get back from the api is as follows.
[ { "ChildIds" : [ ],
"Id" : "1",
"Name" : "Top Level",
"ParentId" : null
},
{ "ChildIds" : [ "51" ],
"Id" : "22",
"Name" : "LevelA - 1",
"ParentId" : "1"
},
{ "ChildIds" : [ "38",
"26"
],
"Id" : "24",
"Name" : "LevelA - 2",
"ParentId" : "1"
},
{ "ChildIds" : [ ],
"Id" : "38",
"Name" : "LevelB - 1",
"ParentId" : "24"
},
{ "ChildIds" : [ ],
"Id" : "26",
"Name" : "LevelB - 2",
"ParentId" : "24"
},
{ "ChildIds" : [ ],
"Id" : "51",
"Name" : "LevelB - 3",
"ParentId" : "22"
},
{ "ChildIds" : [ "43",
"21"
],
"Id" : "36",
"Name" : "LevelC - 1",
"ParentId" : "26"
},
{ "ChildIds" : [ ],
"Id" : "43",
"Name" : "LevelD - 1",
"ParentId" : "36"
},
{ "ChildIds" : [ ],
"Id" : "21",
"Name" : "LevelD -2",
"ParentId" : "36"
}
]
I have managed to get this working by using hard coded select elements but want to make this dynamic.
Html
<div class="container">
<div ng-controller="organisationalUnitCtrl">
<select class="form-control" ng-model="root" ng-options="ou.Name for ou in ous | filter:{ParentId:'!'}">
<option value="">-- choose organisation unit --</option>
</select>
<select class="form-control" ng-model="child" ng-options="ou.Name for ou in ous | filter:{ParentId:root.Id}">
<option value="">-- choose organisation unit --</option>
</select>
<select class="form-control" ng-model="child2" ng-options="ou.Name for ou in ous | filter:{ParentId:child.Id}">
<option value="">-- choose organisation unit --</option>
</select>
<select class="form-control" ng-model="child3" ng-options="ou.Name for ou in ous | filter:{ParentId:child2.Id}">
<option value="">-- choose organisation unit --</option>
</select>
</div>
</div>
Controller
bristowRiskApp.controller('organisationalUnitCtrl',
function organisationalUnitCtrl($scope, organisationalUnitData) {
$scope.ous = organisationalUnitData.getOrganisationalUnit();
}
);
Service
bristowRiskApp.factory('organisationalUnitData', function ($http, $q) {
return {
getOrganisationalUnit: function () {
var deferred = $q.defer();
$http({ method: 'GET', url: 'http://localhost:53995/api/organisationalunit' }).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
}
});
I have read that you should not manipulate the DOM in the controller. So, I am guessing that I should create a directive for my select element that listens for onChange events and creates the new select element? How do I do this? Are there any examples out there that I could learn from?
One other issue I face with my hard coded example is that changing a value in a select only ripples to the next combo. For example, if values were selected in all four select boxes, changing a value in the second one would correctly reset the third box but the fourth will still contain the selected option. I thought the change would be rippled all the way down.
Thanks
Steven
Let me know if/why this doesn't work and I'll fix it accordingly. I think the key fact is in the options repeater you weren't using the syntax to specify the ID of the option - you were just doing its label.
http://jsfiddle.net/KVdqb/
HTML
<div ng-app="bristowRiskApp" ng-controller="organisationalUnitCtrl">
$scope.selections: <pre>{{ selections | json }}</pre>
<div ng-repeat="i in range(selections.length - 1)">
<cascade-select data="data" parent-id="selections[i]" selected-id="selections[i + 1]"></cascade-select>
</div>
</div>
Javascript
var bristowRiskApp = angular.module('bristowRiskApp', []);
bristowRiskApp.controller('organisationalUnitCtrl',
function organisationalUnitCtrl($scope) {
$scope.data = [ /* ... */ ];
$scope.selections = [ null, null ];
$scope.$watch('selections', function (value) {
if (value[value.length - 1] !== null || value.length < 2) {
value.push(null);
} else {
var index = value.indexOf(null, 1);
if (0 < index && index < value.length - 1) {
$scope.selections = value.slice(0, index);
}
}
}, true);
// Helper function.
$scope.range = function (n) {
var result = [];
for (var i = 0 ; i <n; i++) {
result.push(i);
}
return result;
};
});
bristowRiskApp.directive('cascadeSelect', function () {
return {
restrict: 'E',
replace: true,
scope: {
parentId: '&',
selectedId: '=',
data: '='
},
template: '<select ng-show="(data | filter:byId).length > 0" ng-model="selectedId" ng-options="d.Id as d.Name for d in data | filter:byId"><option value="">-- choose organisation unit --</option></select>',
link: function (scope, element, attrs) {
scope.byId = function (d) {
return d.ParentId === scope.parentId();
};
}
}
});

Resources