Angular javascript array is empty? - angularjs

Angular javascript array is empty?
I have an array of checkboxes databound to an angular scoped list
I need to check a few checkboxes and send bind them to a second angular scoped array:
My HTML:
<tr ng-repeat="item in pagedItems[currentPage]"
ng-controller="DealerComMaintainCtrl">
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}"
ng-value="item.IdArticle"
ng-checked="selected.indexOf(item.IdArticle) > -1"
ng-click="toggleSelect(item.IdArticle)" />
</td>
<td>
<a href="/Dealercoms/ArticleDownload?FileName={{item.FileName}}&IdArticle={{item.IdArticle}}"
class="btn btn-xs btn-total-red btn-label"><i class="ti ti-download"></i></a>
</td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
And JS in the controller:
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
} else {
$scope.selected.splice(index, 1)
}
}
$scope.ArchiveDocs = function() {
var selectedoptionz = $scope.selection;
console.log(selectedoptionz);
};

I tried your code and i fixed the problem, by adding the controller on an element above the ng-repeat. The alert is only to check, what is in the selected-array. This is the code, which works fine on my system:
<html>
<head>
</head>
<body ng-app="app">
<table ng-controller="DealerComMaintainCtrl">
<tbody>
<tr ng-repeat="item in pagedItems" >
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}" ng-value="item.IdArticle" ng-checked="selected.indexOf(item.IdArticle) > -1" ng-click="toggleSelect(item.IdArticle)" />
</td>
<td><i class="ti ti-download"></i></td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
</tbody>
</table>
<!-- jQuery -->
<script src="./jquery-2.1.4/jquery.min.js"></script>
<!-- AngularJS -->
<script src="./angular-1.4.5/angular.min.js"></script>
<script>
var app = angular.module("app", []);
app.controller("DealerComMaintainCtrl", function($scope){
$scope.pagedItems = [
{IdArticle: 1, Title: "test1", Archive: "archiv1"},
{IdArticle: 2, Title: "test2", Archive: "archiv1"},
{IdArticle: 3, Title: "test3", Archive: "archiv1"},
{IdArticle: 4, Title: "test4", Archive: "archiv1"}
];
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
}
else {
$scope.selected.splice(index, 1)
}
alert(JSON.stringify($scope.selected));
}
});
</script>
</body>
</html>
Just try it, i hope it solve your problem...

Related

angular, select with dynamic disabled

Now I am trying to select box with disabled.
When $shop.products.product[i].productId is changed by selectBox, I want that value disabled in select box option.
for example, if i select 3 in select box on second row, then select box option 1,3 are disabled.
so i register $watch witch resync isDisabled field when $shop.products[i].productId is changed.
i don't know why $watch is no calling. help me please.
// Code goes here
angular.module("myApp")
.controller("myCtrl", function($scope) {
$scope.shop = {
"id" : 'shop1',
"products" : [
{"productId" : 1,"desc" : 'product1'},
{"productId" : 2,"desc" : 'product2'}
]
};
$scope.allSelectBoxItems = [
{"id" : 1, "isDisabled" : true},
{"id" : 2, "isDisabled" : true},
{"id" : 3, "isDisabled" : false},
{"id" : 4, "isDisabled" : false}
];
$scope.addWatcher = function(index){
console.log('register watcher to ' + index);
$scope.$watch('shop.product[' + index + '].productId', function(newValue, oldValue){
console.log('watcher envoked');
if (newValue != oldValue) {
var selected = $scope.shop.products.map(function (product) {
return product.productId;
});
for (var i = 0; i < $scope.allSelectBoxItems.length; i++) {
var isSelected = selected.includes($scope.allSelectBoxItems[i].productId);
console.log(isSelected);
$scope.allSelectBoxItems.isDisabled = isSelected;
}
}
});
}
angular.forEach($scope.shop.products, function(value, index){
$scope.addWatcher(index);
});
$scope.addProduct = function(){
var nextProductId = $scope.shop.products.length + 1;
var newProduct = {"productId" : nextProductId ,"desc" : 'product' + nextProductId};
$scope.shop.products.push(newProduct);
$scope.addWatcher(nextProductId - 1);
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-animate.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-touch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<script>
angular.module("myApp", ['ngAnimate', 'ui.bootstrap'])
</script>
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
<div>
<table class="table">
<tbody>
<tr>
<th>id</th>
<td>{{shop.id}}</td>
</tr>
<tr>
<td>
products
<br>
<button type="button" class="btn btn-default" ng-click="addProduct()"><span class="glyphicon glyphicon-plus" aria-hidden="true" style="margin-right:4px"></span>add product</button>
</td>
<td>
<table class="table">
<tbody>
<tr>
<td>producId</td>
<td>desc</td>
</tr>
<tr ng-repeat="product in shop.products">
<td>
<select ng-model="product.productId" ng-options="selectBoxItem.id as selectBoxItem.id disable when selectBoxItem.isDisabled for selectBoxItem in allSelectBoxItems"></select>
</td>
<td>
{{product.desc}}
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

AngularFire searching key node and assign to variable

I 'm working on my AngularFire project. I've a database something like this https://dinosaur-facts.firebaseio.com/. What I'm doing is first searching the key like the dinosaurs child such as "linhenykus" and storing its keys and values to other $scope variable.
my code in controller
var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs" + "/" + $scope.dinoID); //$scope.dinoID is variable containg dino keys
$scope.detRef = $firebaseArray(ref);
I'm getting the output like
[{"$value":-85000000,"$id":"appeared","$priority":null},{"$value":0.6,"$id":"height","$priority":null},{"$value":1,"$id":"length","$priority":null},{"$value":"theropoda","$id":"order","$priority":null},{"$value":-75000000,"$id":"vanished","$priority":null},{"$value":3,"$id":"weight","$priority":null}]
How to fetch the keys and values?
Use ngRepeat directive, as below:
<tr ng-repeat="obj in array track by $index">
To filter the array you can use the filter of Angular:
<tr ng-repeat="obj in array | filter: criteria track by $index">
Here's an example:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$filter'];
function MainCtrl($scope, $filter) {
$scope.criteria = {};
$scope.array = [
{
"$value":-85000000,
"$id":"appeared",
"$priority":null
},
{
"$value":0.6,
"$id":"height",
"$priority":null
},
{
"$value":1,
"$id":"length",
"$priority":null
},
{
"$value":"theropoda",
"$id":"order",
"$priority":null
},
{
"$value":-75000000,
"$id":"vanished",
"$priority":null
},
{
"$value":3,
"$id":"weight",
"$priority":null
}
];
$scope.getObj = function(value, id) {
$scope.obj = $filter('filter')($scope.array, {
"$value": value,
"$id": id
})[0];
}
$scope.getObj("theropoda", "order");
}
})();
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" placeholder="Search by value" ng-model="criteria.$value">
<input type="text" placeholder="Search by id" ng-model="criteria.$id">
<!-- Note that this button is just as an example to change the object displayed below -->
<button type="button" ng-click="getObj()">Change the value of object</button>
<hr>
Obj: <span ng-bind-template="Value: {{obj.$value}}, Id: {{obj.$id}}"></span>
<p></p>
<table width="100%">
<thead>
<tr>
<th>Value</th>
<th>Id</th>
<th>Priority</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="obj in array | filter: criteria track by $index">
<td ng-bind="obj.$value"></td>
<td ng-bind="obj.$id"></td>
<td ng-bind="obj.$priority"></td>
</tr>
</tbody>
</table>
</body>
</html>

Getting AngularJS orderBy to sort both directions

I'm attempting to setup a clickable table column header that sort Ascending when first clicked, and Descending when clicked again. My ascending sort is working fine, but I'm not sure how to setup an expression within my OrderBy to sort Descending
My setup thus far:
Table html has something like
<th ng-click="sort('LastName')">Last Name</th>
My sort method looks like
scope.sort = function (columnName) {
if (angular.isDefined(scope.filter)) {
if (scope.filter.SortColumn == columnName) {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = scope.filters.SortDirection == "Asc" ? "Desc" : "Asc";
} else {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = "Asc";
}
}
};
And my ng-repeat looks as follows
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn">
How can I get the SortDirection to factor into the orderBy?
To simply reverse you'd change it to this:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : true">
It'd be best if you used a boolean in your controller, but this should work too:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : filter.SortDirection === 'Desc'">
And just for fun, here's how I do sorting with filtering in my tables.
Controller:
$scope.search = { query: ''};
$scope.sort = { field: 'defaultField', descending: true};
$scope.order = function(newValue) {
if(newValue === $scope.sort.field) {
$scope.sort.descending = !$scope.sort.descending;
} else {
$scope.sort = {field: newValue, descending: false};
}
};
$scope.filteredDocuments = function() {
var a = $filter('filter')($scope.documents, {$:$scope.search.query});
var b = $filter('orderBy')(a, $scope.sort.field, $scope.sort.descending);
return b;
};
A search box for filtering:
<input type="text" ng-model="search.query">
A column header:
<th nowrap>
<a href ng-click="order('size')">Size </a>
<i ng-show="sort.field === 'size' && !sort.descending" class="fa fa-sort-amount-asc"></i>
<i ng-show="sort.field === 'size' && sort.descending" class="fa fa-sort-amount-desc"></i>
</th>
The row binding:
<tr ng-repeat="d in filteredDocuments()" >
A simplified version of the above answer:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')" >Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:mySortOrder">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.sorts={};
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
if(x in $scope.sorts) {
$scope.sorts[x]=!$scope.sorts[x];
} else {
$scope.sorts[x]=false;
}
$scope.mySortOrder=$scope.sorts[x];
}
});
</script>
</body>
</html>

How to add checkbox values to an array in AngularJS?

Someone help me please!
Lets say I have an a list of a checkboxes, each checkbox have an ID.
I would like to $scope an array with checked checkboxes IDs.
<div ng-app="myapp">
<div ng-controller="ctrlParent">
<table>
<tr ng-repeat="(key, value) in providers">
<td><input type="checkbox" ng-model="ids[value.Id]"> {{value}} </td>
</tr>
</table>
{{ids}}
</div>
And my controller:
var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope){
$scope.providers = [{Id:5},{Id:6},{Id:8},{Id:10}];
$scope.ids = {};
});
Now my array output (if all check boxes are checked) is: {"5":true,"6":true,"8":true,"10":true}
And I would like: [{Id:5},{Id:6},{Id:8},{Id:10}]
this is a possible solution:
<input type="checkbox" ng-model="ids[$index]" ng-true-value="
{{value}}" ng-false-value="{{undefined}}"/>{{value}}
In this way, you will have an array of objects, because you are assigning ids[$index] = value.
There is a cons however: when you double check a checkbox, you will have an empty element in the array.
var app = angular.module('myapp', []);
app.controller('ctrlParent', function($scope) {
$scope.providers = [{
Id: 5
}, {
Id: 6
}, {
Id: 8
}, {
Id: 10
}];
$scope.ids = [];
$scope.$watchCollection('ids', function(newVal) {
for (var i = 0; i < newVal.length; ++i) {
console.log(newVal[i]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="ctrlParent">
<table>
<tr ng-repeat="(key,value) in providers">
<td>
<input type="checkbox" ng-model="ids[$index]" ng-true-value="{{value}}" ng-false-value="{{undefined}}" />{{value}}
</td>
</tr>
</table>{{ids}}</div>
</div>
http://jsfiddle.net/b9jj0re2/3/
<input type="checkbox" ng-model="ids[$index]" ng-true-value="{{value}}" >
Addign the ng-true-value directive will solve the problem
and in controller change the ids from object to array
plunker

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

Resources