How to use an array on ng-model - angularjs

This is my code http://plnkr.co/edit/oxtojjEPwkKng9iKkc14?p=preview
And I want to save object of sport and punctuation in an array, if there are one or more sports selected save it in the array like this:
likes[
{sport: 'futball', points: 1}, {sport: 'tennis', points: 1}
]
thanks!

You have to keep practicing your English a little bit more (you can ask me on the comment section in spanish if you are strugling)
I think what you are trying to do is to have a single select to be able to choose the sport and score,
Html:
<body ng-app="myapp">
<div class="main-container" ng-controller="main" ng-init="darr.dept=dept2">
<div class="client-area">
<label fo.table-container tabler="txt">Score</label>
<input type="text" id="name-txt" placeholder="Assign the score" ng-model="name">
<br />
Sport
<select ng-model="dept" ng-options="deptOpt.value as deptOpt.name for deptOpt in deptList"></select>
<br />
<button ng-click="add()">Add Item</button>
<table id="tab">
<thead>
<tr id="trow">
<th>Score</th>
<th>Sport</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ar in arr">
<td>{{ar.name}}</td>
<td>{{ar.dept}}</td>
<td>
<button ng-click="del($index)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
js:
var app = angular.module("myapp", []);
app.controller('main', function ($scope) {
$scope.arr = [];
$scope.deptList = [{
name: 'Football',
value: 'football'
}, {
name: 'Tennis',
value: 'Tennis'
}, {
name: 'Baseball',
value: 'baseball'
}];
$scope.dept = "football";
$scope.name = "";
$scope.add = function () {
this.arr.push({
name: this.name,
dept: this.dept
});
};
$scope.del = function (ind) {
this.arr = this.arr.splice(ind, 1);
};
$scope.editStudent = function(student) {
console.log(student);
};
});
https://jsfiddle.net/azweig/v5kbsudy/1

Related

AngularJS : ng-model not working in multiple drop down

I am trying to create dynamic rows based on button click. The rows have drop down boxes. The issue is when I add new row and select an option in the new row the options which I selected in previous rows are also changing, I mean the previous rows options are not binding properly.
My HTML code :
<div id="features" ng-controller="featuresCtrl">
<br>
<div class="row">
<div class="form-group col-md-6">
<table cellpadding="15" cellspacing="10">
<thead>
<tr>
<th style="text-align: center;">Feature</th>
<th style="text-align: center;">Type</th>
<th style="text-align: center;">Value</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr ng-repeat="r in rows">
<td>
<select ng-model="r.data.model" ng-options="option.name for option in data.availableOptions"
ng-change="getValues(r.data.model.name)">
<option value="">Select Feature</option>
</select>
</td>
<td>
<select ng-model="r.updateData.model" ng-options="option.name for option in updateData.availableOptions"
ng-change="getBinSet(r.updateData.model.name)">
<option value="">Select Type</option>
</select>
</td>
<td>
<select ng-model="r.binData.model" ng-options="option.name for option in binData.availableOptions">
<option value="">Select Value</option>
</select>
</td>
<td ng-if="showAdd">
<div class="text-center">
<button ng-click="addRow()">Add</button>
</div>
</td>
<td ng-if="showAdd">
<div class="text-center">
<button ng-click="remove($index)">Remove</button>
</div>
</td>
</tr>
<tr>
<td></td>
<td style="align-self: center;">
<button style="align-self: center" ng-click="submitForm(rows)">Submit</button>
</td>
<td></td>
</tr>
</tbody>
</table>
<br>
</div>
My angular JS code :
'use strict';
var testControllers = angular.module('testControllers');
testControllers.controller('featuresCtrl', ['$scope','$route','$filter', '$http', '$location','$window','$timeout', 'NgTableParams',
function($scope, $route, $filter, $http, $location, $window, $timeout, NgTableParams) {
$scope.rows = [{}];
$scope.nrows = [];
$scope.showAdd = false;
$scope.addRow = function() {
$scope.rows.push({
});
};
$scope.remove = function(index) {
$scope.rows.splice(index, 1);
};
$scope.submitForm = function(rows) {
console.log("rows", rows);
};
$scope.data = {
model: null,
availableOptions: [
{ name: 'TestA'},
{ name: 'TestB'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
$scope.getValues = function (featureType) {
console.log("getValues", featureType);
$scope.showAdd = false;
if (featureType != null) {
$http.get('/getPropensityValues.do', {params: {'featureType': featureType}}).success(function (data) {
var test = [];
angular.forEach(data, function (item) {
test.push({name: item});
});
$scope.updateData = {
model: null,
availableOptions : test
};
});
}
};
$scope.getBinSet = function (featureType) {
console.log("getBinSet", featureType);
$scope.showAdd = true;
if (featureType != null) {
$scope.binData = {
model: null,
availableOptions: [
{name: '1'},
{name: '2'},
{name: '3'},
{name: '4'},
{name: '5'},
{name: '6_10'},
{name: '10_15'},
{name: '16_20'},
{name: '21_25'},
{name: '26_30'},
{name: '31_35'},
{name: '36_40'},
{name: '41_45'},
{name: '46_50'},
{name: '>50'}
]
};
}
};
}]);
Can some one tell me what I am doing wrong here ? I tried with another example - https://plnkr.co/edit/Jw5RkU3mLuGBpqKsq7RH?p=preview
Even here I am facing same issue when selecting the 2nd row 1st row also changing. Is it wrong to use r.data.model to bind each row's values ?
I updated your plunker to work:
https://plnkr.co/edit/4sJHHaJPEuYiaHjdnFBp?p=preview
You weren't defining what the model was when you were redefining the options menus (side note: you should leverage underscore.js's difference function within a filter to create the appropriate display options dynamically)
Anyway, in your addRow() function, I changed it from this:
if(val=== 'TestB') {
$scope.data1 = {
model: null,
availableOptions: [
{ name: 'TestA'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
}
to this:
if(val=== 'TestB') {
$scope.data1 = {
model: 'TestB',
availableOptions: [
{ name: 'TestA'},
{ name: 'TestC'},
{ name: 'TestD'}
]
};
}
Let me know if this helps
UPDATE:
I recreated the functionality from scratch because I think you were overthinking things. All that is needed here is very simple ng-repeat, ng-options, and ng-model bindings.
<tr ng-repeat="r in rows track by $index">
<td>
<select ng-model="r.name"
ng-options="option.name as option.name for option
in availableOptions">
<option value="">Select Value</option>
</select>
</td>
<td>
<input type="button" ng-click="addRow()" value="Add">
</td>
<td>
<input type="button" ng-click="deleteRow($index)"
value="Delete">
</td>
</tr>
and for the angular
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.rows = [{name:""}];
$scope.addRow = function(){
$scope.rows.push({name:""});
}
$scope.availableOptions = [
{ name: 'TestA'},
{ name: 'TestB'},
{ name: 'TestC'},
{ name: 'TestD'}
];
$scope.deleteRow = function(index){
$scope.rows.splice(index,1);
}
});
I didn't throw in the difference thing yet, but it should be easy.

What triggers a function call in other column when ngmodel changes in first column?

Consider the snippet:
JS
var mod = angular.module('module', []);
mod.controller('controller', function($scope) {
$scope.items = [{
id: 1,
label: 'aLabel',
subItem: {
name: 'aSubItem'
}
}, {
id: 2,
label: 'bLabel',
subItem: {
name: 'bSubItem'
}
}]
$scope.getValue = function(ngmodel) {
// some code goes here...
}
});
HTML
<body ng-controller='controller'>
<div>
<table>
<tr ng-repeat='count in counter'> // 5 times
<td>
<select ng-options="item.id as item.label for item in items"
ng-model="selected[$index]">
</select>
</td>
<td>
{{getValue(1)}}
</td>
<td>
</td>
</tr>
</table>
</div>
</body>
As soon as I select some value from the dropdown (select tag) in the first column, I notice that the function in the second column is triggered? What is the reason for this? What exactly is happening behind the scenes?
The reason is you are doing it inside ng-repeat
<tr ng-repeat = 'count in counter'>
You need to pass the object on the controller, in order to do some action on the same.
{{getValue(obj)}}

passing the value from table to textbox in angularjs

I am trying to pass the value from table to text box in angularjs. value should be pass when i click 'pass the value' button. can anyone help me with this?
my code is shared below:
angular.module('app', [])
.controller('controller', function($scope) {
$scope.array = [{
id:1,
name: 'name1',
address: 'address1'
}, {
id:2,
name: 'name2',
address: 'address2'
}, {
id:3,
name: 'name3',
address: 'address3'
}];
$scope.edit=function(id){
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body ng-app="app" ng-controller="controller" class="container">
<table class="table table-condensed">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
<tr ng-repeat="item in array" >
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.address}}</td>
<td><button ng-click="edit(item.id)">pass the value</button></td>
</tr>
</table>
<form>
name <input type="text" ng-model="item.name" />
address <input type="text" ng-model="item.address"/>
</form>
</body>
Instead of just passing the id, pass the whole item to the edit function:
<button ng-click="edit(item)">
Then you can set the item on scope to the passed item:
$scope.edit=function(item){
$scope.item = item;
};
Plunkr
You should assign your index in a variable in click function. Like
<button ng-click=" newIndex = $index; ">pass the value</button>
And fetch this indexed value from array. Like
name <input type="text" ng-value="array[newIndex].name" />
address <input type="text" ng-value="array[newIndex].address"/>
Make sure to declare newIndex in your controller first. Like
$scope.newIndex = null;

angularjs ng-repeat inside ng-repeat,the inside array can't update

I come from China,my English very poor,so I do a demo.how can I update array inside ng-repeat?
The HTML:
<body ng-app="main" ng-controller="DemoCtrl">
<table ng-table class="table">
<tr ng-repeat="user in users">
<td data-title="'Name'">{{user.name}}</td>
<td data-title="'Age'">{{user.age}}</td>
<td>
{{user.spms|json}}
<div ng-repeat="u in user.spms">
<span ng-bind="u"></span>
<input type="text" ng-model="u" ng-change='updateArray($parent.$index, $index, u)'>
</div>
</td>
</tr>
</table>
</body>
The JS:
var app = angular.module('main', []).
controller('DemoCtrl', function($scope) {
$scope.users = [{
name: "Moroni",
age: 50,
spms: [
6135.7678,
504.4589,
2879.164,
669.7447
]
},
{
name: "seven",
age: 30,
spms: [
34135.7678,
5034.42589,
22879.1264,
63469.72447
]
}
];
$scope.updateArray = function(parent, index, u) {
$scope.users[parent].spms[index] = u * 1; // multiply by one to keep the value a Number
}
})
There are issues here are every update is changing the scope, so you can only change one time them click then change - so I would recommend add a update values button and implementing more or less the same logic to update the array values.
DEMO

angularJS: Filter JSON Data w.r.t Date Range

I am completely new to AngularJS. Here is my HTML code
<div ng-controller="DateRangeCtrl">
<div class="container">
<div class="form-horizontal">
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt1" is-open="opened1" max="maxFromDate" ng-change="setMinToDate()"/>
<button class="btn btn-sm" ng-click="open1($event)"><span class="glyphicon glyphicon-calendar"></span></button>
</div>
<div class="form-horizontal">
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt2" is-open="opened2" min="minToDate" max="maxToDate" ng-change="filterDateAdded()"/>
<button class="btn btn-sm" ng-click="open2($event)"><span class="glyphicon glyphicon-calendar"></span></button>
</div>
<p><strong>Selected From Date: </strong> {{dt1 | date:'mediumDate'}}</p>
<p><strong>Selected To Date: </strong> {{dt2 | date:'mediumDate'}}</p>
</div>
<hr />
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Date Added</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items | orderBy:mySortFunction ">
<td>{{item.ID}}</td>
<td>{{ parseDate(item.dateAdded) | date:'longDate'}}</td>
</tr>
</tbody>
</table>
</div>
The following is my angular code:
testApp.config(function (datepickerConfig, datepickerPopupConfig) {
datepickerConfig.showWeeks = false;
datepickerPopupConfig.showButtonBar = false;
});
testApp.controller('DateRangeCtrl', function($scope) {
$scope.items = [
{ID: "1", dateAdded: "01-04-2013"},
{ID: "2", dateAdded: "12-01-2013"},
{ID: "3", dateAdded: "12-31-2013"},
{ID: "4", dateAdded: "01-12-2014"},
{ID: "5", dateAdded: "03-04-2014"}
];
$scope.parseDate = function(input){
var parts = input.split('-');
var newParts = new Date(parts[2], parts[0]-1, parts[1]); // Note: months are 0-based
return newParts;
}
$scope.open1 = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened1 = true;
};
$scope.maxFromDate = new Date();
$scope.maxToDate = new Date();
$scope.setMinToDate = function (){
$scope.dt2 = null;
$scope.minToDate = $scope.dt1;
};
$scope.open2 = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened2 = true;
};
});
How can i filter rows based on selected dates? For e.g. if i select "01/01/2014" in the "From" datePicker then i should be able to see all the rows whose "Date Added" column has value more than "January 1, 2014". The output will be rows with ID: 4 and 5.
It should behave the literal equivalent way when the "To" datePicker is selected
Please help me out. i'm stuck!
Update:
HTML
<tr ng-repeat="item in items | filter:dateFilter ">
JS
$scope.dateFilter = function (item) {
return (item.dateAdded < $scope.dt2);
};
Am i doing anything wrong? It still doesn't work....
By some hit n trial method, i eventually got it right. The problem was the "item.dateAdded" string had to be converted to Date object. Solution is adding the following piece of code in the js file:
$scope.filterDateAdded = function (){
if($scope.dt1 != null)
{
$scope.dateFilter = function (item) {
return ($scope.parseDate(item.dateAdded) >= $scope.dt1 && $scope.parseDate(item.dateAdded) <= $scope.dt2);
};
}
};
Cheers!
Change your code like this
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt2" is-open="opened2" min="minToDate" max="maxToDate" ng-model="search" ng-change="filterDateAdded()"/>
<tr ng-repeat="item in items | filter:dateFilter">
$scope.filterDateAdded=function()
{
$scope.dateFilter = function () {
var result=[];
for(var i in $scope.item)
{ if($scope.item[i].dateAdded >$scope.search)
{
result.push($scope.item[i]);
}
}
return result;
};
}

Resources