Restrict function action to row operated by user - javascript

I can't find a way to restrict the action triggered by ng-change to only the row operated by the user. So, if user selects "League" on dropdown 1, two dropdowns should be displayed on the "Available Items" column. The one from the top lets you select a sport, when selected, down dropdown should display league options. The problem now is that all dropdowns from the table get populated (you can see that if you select "league" on another row's dropdown, league options are already displayed before you select your sport). What I need is to restrict function's action only to row operated by user.
Here's a fiddle:
https://embed.plnkr.co/kAiLw40hUvnLk9jv86aj/
<div class="col-md-12 limitObjects">
<h4>Limit Object: </h4>
<div style="overflow: auto; max-height: 500px; height: 100%">
<table border="0" class="table-bordered myTable" >
<tbody>
<tr ng-repeat="item in userMappings" ng-model="item">
<td class="col-md-4">
{{item.idsport}}, Game Type {{item.idgametype}}, {{item.name}} (Current limit {{item.value}}) {{item.mapped}}
</td>
<td class="col-md-3 mapType" style="padding-bottom: 25px; padding-left: 15px" >
<h4>Mapping Type: <span style="font-size:0.8em">{{mapping.name}}</span> </h4>
<select ng-model="item.mapping" ng-change="which(item, $index, event)" ng-options="mapping.name for mapping in mappingType" se-change=''></select>
</td>
<td class="col-md-4" style="padding-bottom: 25px; padding-left: 10px">
<h4>Available Items:</h4>
<select ng-show="item.buau" ng-model="sport" ng-change="getID(sport, $index, $event); table($event)" ng-options="sport.name for sport in sportsList"></select>
<select ng-show="item.buau == false" ng-model="sportLeague" ng-change="getLeaguecategories(sportLeague, $index, $event)" ng-options="sportLeague.name for sportLeague in sportsList" style="float: left;"></select>
<select ng-show="item.buau == false" ng-model="selectedLeague" ng-change="getID(selectedLeague, $index)" ng-options="selectedLeague.name for selectedLeague in leagueList" ></select>
</td>
<td class="col-md-4" style="padding-bottom: 25px; padding-left: 15px">
<h4>Subjects: </h4>
<select ng-model="subject" ng-change="getsubjectID(subject, $index)" ng-options="subject.description for subject in limitSubject"></select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
$scope.mappingType = [{name: "Sport"}, {name: "League"}, {name: "No Mapping"}];
$scope.sportsList = [{id : 34, name : "[Default]"}, {id: 15, name : "Alpine Skiing"}, { id : 8, name : "American Football" }, { id : 23, name : "Australian Rules"}];
$scope.getLeaguecategories = function($event){
$scope.leagueList = [{"name": "NFL"}, {"name": "NCAA"}, {"name": "All others"}];
}
$scope.userMappings =[{"id":"1","idgametype":"81","idsport":"NFL","mapped":"0","name":"Side","online":"1","profilelimitkeyid":"1","value":"3000"},{"id":"2","idgametype":"81","idsport":"NFL","mapped":"4","name":"Total","online":"1","profilelimitkeyid":"1","value":"3000"},{"id":"3","idgametype":"81","idsport":"NFL","mapped":"0","name":"IfBets","online":"1","profilelimitkeyid":"1","value":"500"},{"id":"4","idgametype":"81","idsport":"NFL","mapped":"0","name":"MoneyLine","online":"1","profilelimitkeyid":"1","value":"2000"},{"id":"5","idgametype":"81","idsport":"NFL","mapped":"1","name":"Parlays","online":"1","profilelimitkeyid":"1","value":"700"},{"id":"6","idgametype":"81","idsport":"NFL","mapped":"0","name":"Related","online":"1","profilelimitkeyid":"1","value":"0"},{"id":"7","idgametype":"81","idsport":"NFL","mapped":"0","name":"Reverses","online":"1","profilelimitkeyid":"1","value":"500"},{"id":"8","idgametype":"81","idsport":"NFL","mapped":"2","name":"Teasers","online":"1","profilelimitkeyid":"1","value":"0"}];
$scope.which = function( item, index ) {
if ( item.mapping.name === "Sport" ){
item.buau = true;
} else if ( item.mapping.name === "League" ) {
item.buau = false;
} else if ( item.mapping.name === "No Mapping" ){
}
}

Related

How to set the id attribute of an array dynamically with angularjs, HTML?

I am trying to get a dynamic id to my array(details) within my ng-repeat so that I can bind to different data with different view of child div. Let me show an example.
<div class="row">
<div class="panel-heading bgOrg col-xs-12 col-sm-12 col-md-12 col-lg-12 header-container ">
<div class="col-sm-1 col-xs-12 pull-left "></div>
<div class="col-sm-1 col-xs-12 header-cell">Request# </div>
<div class="col-sm-1 col-xs-12 header-cell ">Id</div>
</div>
<div ng-repeat="data in friends">
<div class="row panel panel-body ">
<div class="col-xs-1">
<div class="handpointer glyphicon glyphicon-plus"
data-ng-click="collapse($event, data.id)"
data-target="#view_{{data.id}}"
data-toggle="collapse" aria-expanded="false">
</div>
</div>
<div class="col-sm-1 col-xs-12" data-ng-bind="data.requestId"></div>
<div class="col-sm-1 col-xs-12" data-ng-bind="data.id"></div>
</div>
<div class="collapse" id="view_{{data.id}}">
<div class="col-sm-offset-1">
<table class="table-condensed responsive-table">
<tr class="row">
<th><input class='header-checkbox' type='checkbox' /> </th>
<th>Id</th>
<th>Instance</th>
</tr>
<tr class="row" ng-repeat=" item in details[{{data.id}}]">
<td><input class='header-checkbox' type='checkbox' /></td>
<td data-ng-bind="item.id"></td>
<td data-ng-bind="item.name"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
My problem is when I click on my parent div, I want to map child div with new data, Is it possible to set a dynamic ID in this concept?
Js:
$scope.details = [];
$scope.collapse = function (event, requestId) {
var deferred = $q.defer();
var idx = 0;
service.getDetail(requestId)
.then(function (response) {
$scope.details[requestId] = response;
deferred.resolve();
}, function (error) {
console.log(error);
deferred.reject();
});
return deferred.promise;
}
};
One thing that is standing out is that you don't want to interpolate here.
<tr class="row" ng-repeat=" item in details[{{data.id}}]">
to
<tr class="row" ng-repeat="item in details[data.id]">
Here is a rudimentary example of where I think you are trying to get.
JS
// You have a list of things. Probably via $http.get.
$scope.listOfThings = [
{ id: 0, name: 'thing0' },
{ id: 1, name: 'thing1' },
{ id: 2, name: 'thing2' }
]
$scope.loadedDetails = {};
// Somehow you load the details into your hash, with a specific key.
$scope.getDetails = function(id) {
$scope.loadedDetails[id] = theDetails[id];
// If you want to just keep track of the last thing that was clicked,
// Just store the id...
$scope.active = id;
}
// These would come from the backend normally.
var theDetails = {};
theDetails[0] = [ { detail: 'thing 0 dtl 1' },
{ detail: 'thing 0 dtl 2' } ];
theDetails[1] = [ { detail: 'thing 1 dtl 1' },
{ detail: 'thing 1 dtl 2' } ];
theDetails[2] = [ { detail: 'thing 2 dtl 1' },
{ detail: 'thing 2 dtl 2' } ];
HTML
<div ng-controller='ctrl'>
<!-- Iterate over your things, and display details if you click on a thing -->
<ul>
<li ng-repeat="thing in listOfThings" ng-click="getDetails(thing.id)">{{ thing.name }}
<ul>
<li ng-repeat="dtl in loadedDetails[thing.id]">
A Detail: {{ dtl.detail }}
</li>
</ul>
</li>
</ul>
<hr>
<h2>Last Clicked</h2>
<!-- If you just want to show the last thing clicked somewhere else -->
{{ loadedDetails[active] }}
</div>
http://plnkr.co/edit/XQilKCdw0uQXvcBZ0b7a?p=preview

mvc + partial view + check box click event

I have created a partial view and using it in same page for n times. The partial view is placed inside a accordion (div), and when a checkbox is clicked, then text box should be disabled.
When I render the page, which uses the partial view 5 times, and I click the checkbox, then the textbox gets disabled only within the first partial view. The same functionality doesn't work in any of the others.
When I place the debugger in all the partial views it hits, but the textbox doesn't get disabled. This only works in the 1st partial view, but fails in the rest.
Please find the below code..
<table>
<tr>
<th>Select Recurrance:</th>
<th>Start DateTime:</th>
<th>End DateTime:</th>
</tr>
<tr>
<td>
<div style="margin-top: -0.0em;">
<select id="Recurrances" onchange="SubmitRecurrance(this)">
<option selected="selected" value="1">Run Continuosly</option>
<option value="2">Run on Schedule</option>
</select>
<br />
#Html.ValidationMessageFor(model => model.Recurrance)
</div>
</td>
<td>
<div style="margin-top: -0.0em;">
#Html.TextBoxFor(model => model.StartDateTime, new { #class = "form-control date-picker", #placeholder = "Start Date&Time", id = "starttime", onkeyup = "FormDirty();" })
<br />
#Html.ValidationMessageFor(model => model.StartDateTime)
</div>
</td>
<td>
<div style="margin-top: -0.0em;">
#Html.TextBoxFor(model => model.EndDateTime, new { #class = "form-control date-picker", #placeholder = "End Date&Time", id = "endtime", onkeyup = "FormDirty();" })
<br />
#Html.ValidationMessageFor(model => model.StartDateTime)
</div>
</td>
</tr>
<tr>
<td id="divnoenddate">
<div>
<span> No End Date</span>#Html.CheckBox("NoEndDate", false, new { id = "noenddate", onchange = "javascript:ChangeCheckBox()" })
<br />
</div>
</td>
<td id="recureveryoption">
<span style="font-weight:bold;">Recur Every:</span> <div>
<select id="RecurEvery">
<option selected="selected" value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
<option value="4">Yearly</option>
</select>
</div>
</td>
<td>
<div>
<input type="submit" value="Save" style=" width: 8em;height: 2em;text-align: center;padding-top: 6px;background: #0082BF;font-size: 1em; color: #0082BF; cursor:pointer; color:white;font-size: 1em; padding-left:6px; padding-right:6px;padding-bottom:6px;" onclick="SubmitChanges()" />
</div>
</td>
</tr>
</table>
function ChangeCheckBox()
{
if (document.getElementById("Recurrances").value != 1)
{
debugger;
if (document.getElementById('noenddate').checked == true)
{
document.getElementById("endtime").disabled = true;
}
else
{
document.getElementById("endtime").disabled = false;
}
}
}
I'm referring the above partial view as:
<div>
#Html.Partial("~/Views/Settings/ScedularControl.cshtml")
</div>
Sent to parameter index of partial view than use checkbox like, following html helper list item:
#Html.CheckBox("SameModel["+index+"].Checked",false)

Passing selected object model on button press/event trigger

I have a button that currently passes the selected value to the removeContract().
<td class="col-md-1" colspan="1" style="text-align: center; vertical-align: middle;">
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue, contractIndex)"> <= </button>
</td>
<td class="col-md-5" colspan="5">
<label class="control-label">{{item.fields[132].displayName}}</label>
<select size="5" ng-model="ctrl.selectValue">
<option data-ng-repeat="contract in contracts">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
</select>
</td>
However, I need to send back the actual current contract model, called 'contract' above. The function's 1st parameter needs to be the currently selected contract. How would I achieve this?
Some suggestions as per the current code :
Instead of passing whole {{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}] into the ng-model just pass the contract.CONT_ORDNO to identify the selected data from the dropdown.
<option data-ng-repeat="contract in contracts" value="contract.CONT_ORDNO">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
As we already have contracts array of objects inside the controller.Hence, no need to pass the second parameter inside the removeContract function.
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue)"> <= </button>
Based on the selected value we can remove the contract object from the contracts array inside removeContract function with the help of Array filter() method.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.contracts = [
{
"CONT_ORDNO": "1",
"SUPP_NAME": "alpha",
"SUPP_NUM": "0001"
},
{
"CONT_ORDNO": "2",
"SUPP_NAME": "beta",
"SUPP_NUM": "0002"
},
{
"CONT_ORDNO": "3",
"SUPP_NAME": "gaama",
"SUPP_NUM": "0003"
},
{
"CONT_ORDNO": "4",
"SUPP_NAME": "xyz",
"SUPP_NUM": "0004"
}
];
$scope.removeContract = function(selectedVal) {
var removedObj = $scope.contracts.filter(function(item) {
return item.CONT_ORDNO != selectedVal;
});
console.log(removedObj);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<td class="col-md-1" colspan="1" style="text-align: center; vertical-align: middle;">
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue)"> <= </button>
</td>
<td class="col-md-5" colspan="5">
<label class="control-label">{{item.fields[132].displayName}}</label>
<select size="5" ng-model="ctrl.selectValue">
<option data-ng-repeat="contract in contracts" value="{{contract.CONT_ORDNO}}">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
</select>
</td>
</div>

Angular JS multiple select box filter not working properly?

I'm learning angularjs and was struggling with selection as well. I know this question is already answered but wanted to share some more code nevertheless.
In my test I have two listboxes: tournament name and tournament city
tournament city should be unique
When i select tournament name it will show up corresponding tournament name list it coming correct only
When i seclect city in selectbox it wont populate any thing
app.controller('MainCtrl', function($scope) {
$scope.tournaments = [
{ id: 1, name: 'Banglore Cup', city:'Banglore' },
{ id: 2, name: 'Banglore Cup1', city:'Mumbai' },
{ id: 3, name: 'Banglore Cup2', city:'Banglore' },
{ id: 4, name: 'Mumbai Cup1', city:'Mumbai' },
{ id: 5, name: 'Mumbai Cup2', city:'Banglore' }
];
});
<div class="row">
<div class="col s4 input-field ">
<select class="browser-default" name="show-filter" ng-model="tournamentFilter.id" ng-options="eachTournament.id as eachTournament.name for eachTournament in tournaments">
<option value="" selected> All</option>
</select>
</div>
<div class="col s4 input-field ">
<select class="browser-default" name="show-filter" ng-model="tournamentFilter.city" ng-options="eachTournament.city as eachTournament.city for eachTournament in tournaments| unique:'city'">
<option value="" selected> All</option>
</select>
</div>
</div>
</div>
<div class="col s12">
<table class="list_tournament">
<tbody ng-repeat="eachTournament in tournaments | filter:{id:tournamentFilter.id||undefined} | orderBy:'name'">
<tr class="row nomargin">
<td class="col s4 m3 tournament_list_location">
{{eachTournament.name}}
</td>
<td class="tournament_list_location col s12 m3">
{{eachTournament.city}}
</td>
</tr>
</tbody>
</table>
</div>
Can you help me to getting data
Use this custom filter from here to get only unique values : Updated Plunkr
app.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
Html:
Change the filter like below :
<tbody ng-repeat="eachTournament in tournaments | filter:{id:tournamentFilter.id, city: tournamentFilter.city||undefined} | orderBy:'name'">

How to get the Id of current row using knockout Js for hiding the remove button

Is there any way to hide the delete button/div only for first row in knockout js. i have nested templates. and if use $index it hides the remove button but also does the same for nested templates as they will have again the same index.
I had tried many thing but nothing works. I only want to hide the content of logical-div only if is the first row. and this template is repeating with same attributes/values. below is the HTML part.
Thanks in advance for any help.
<ul data-bind="template: { name: 'itemtemplate', foreach: $root.subitemsOf(null) }"></ul>
<script type="text/html" id="itemtemplate">
<li>
<div class="logical-div" style="margin-top: 5px; width:250px; border:1px solid gray;display:inline-block">
<select class='logical-inner-div' data-bind="options: $root.Condition, selectedOptions:logicalConditionSelected , optionsValue: 'logicalConditionVal', optionsText: 'logicalConditionName'" style="width:200px;">
</select>
</div>
<table class="block" style="margin-top: 5px;">
<tr>
<td>
<select data-bind="options: $root.tag, selectedOptions:tagSelected , optionsValue: 'tagVal', optionsText: 'tagName'" style="width:80px;">
</select>
</td>
<td>
<select data-bind="options: $root.isNot,selectedOptions:isNotSelected , optionsValue: 'isNotVal', optionsText: 'isNotName'" style="width:80px;">
</select>
</td>
<td>
<select data-bind="options: $root.alias,selectedOptions:aliasSelected, optionsValue: 'aliasVal', optionsText: 'aliasName'" style="width:300px;">
</select>
</td>
<td>
<img src="<?php echo Yii::app()->baseUrl . '/images/removeitem.gif';?>" alt="Delete">
</td>
<td>
<button class="add-condition btn btn-primary btn-small" data-bind="click: $root.addNestedSegment" >Add Nested Block</button>
</td>
</tr>
<tr>
<td colspan="5">
<div style="margin-top: 5px;">
<ul data-bind="template: {name: 'itemtemplate', foreach: $root.subitemsOf($data)}"></ul>
</div>
</td>
</tr>
</table>
</li>
</script>
Some of JS Part.
function ItemModel(id, parent_id, initialLogicalVal,initialTagVal,initialIsNotVal,initialAliasVal) {
var self = this;
self.id = ko.observable(id);
self.parentId = ko.observable(parent_id);
self.logicalConditionSelected = ko.observable([initialLogicalVal]);
self.tagSelected = ko.observable([initialTagVal]);
self.isNotSelected = ko.observable([initialIsNotVal]);
self.aliasSelected = ko.observable([initialAliasVal]);
}
var viewModel = function RecursiveListViewModel(tasks)
{
var self = this;
// Knock out function for checking the parents
self.subitemsOf = function (item) {
var children = ko.utils.arrayFilter(self.items(), function (arrayItem) {
var parentItemId = (null === item) ? null : item.id();
return arrayItem.parentId() == parentItemId;
});
return children;
};
// Knock out function for checking if there are child for this record for populating nested records
self.hasSubitems = function (item) {
var firstMatch = ko.utils.arrayFirst(self.items(), function (arrayItem) {
return (arrayItem.parentId() == item.id());
});
return (null !== firstMatch); // At least one item found in array
};
// Knock out function for Adding the nested/child segment
self.addNestedSegment = function(item) {
self.items.push(new ItemModel(++ChildId, item.id(),'and','Tag','Is Not',firstAlias));
}
// Knock out function for Adding the Main/Parent segment
self.addMainSegment = function(data, event) {
self.items.push(new ItemModel(++ChildId, null,'and','Tag','Is Not',firstAlias));
}
// Knock out function for Deleting the segment with all of its children
self.removeSegment = function(data,item)
{
self.items.remove(data);
}
}
Instead of using the $index variable, you can check the object reference:
<!-- ko if: $data != $root.items()[0] -->
<div class="logical-div">
</div>
<!-- /ko -->
Or using some observable, like
<!-- ko if: $data != firstItem() -->
<div class="logical-div">
</div>
<!-- /ko -->
self.firstItem = ko.computed(function() { return self.items()[0]; });
The != operator in the sentence check if both objects are the same (if they point to the same object in memory). Because the first rendered element is the same as self.items()[0] then knockout will hide this div element (in this case, the ko if does not hide the element; it does not render it)
Greetings!

Categories