How to pass ng-repeat value to controller - javascript

I am using an ng-repeat directive with filter like so:
<div ng-repeat="person in data">
</div
i.e Showing {{data.length}} Persons. (I am expect to pass the length value to controller)
But i need to pass the filtered length value to controller because i do same logic based on the filtered length value.

1.Method 1
ng-repeat="item in filtered = (data | filter:filterExpr)"
Would create the filtered list.
filtered.length will show the filtered length.
2.Method 2
Use $watch for detecting the filtered length.
$scope.length = $scope.data.length;
$scope.$watch("search", function(query) {
$scope.length = $filter("filter")($scope.data, query).length;
});
Example
var app = angular.module('angularjs-starter', [])
app.controller('MainCtrl', function($scope, $filter) {
$scope.data = [{
"name": "Martin",
"age": 21
}, {
"name": "Peter",
"age": 26
}, {
"name": "Arun",
"age": 25
}, {
"name": "Maxwell",
"age": 22
}];
$scope.counted = $scope.data.length;
$scope.$watch("search", function(query) {
$scope.filteredData = $filter("filter")($scope.data, query);
});
});
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Demo</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input ng-model="search" type="text">
<br>Showing {{data.length}} Persons;
<br>Filtered {{filteredData.length}}
<ul>
<li ng-repeat="person in filteredData">
{{person.name}}
</li>
</ul>
</body>
<script>
</script>
</html>

Related

Angular - Binding the following data via ng-options for a select field

Given the following code:
http://jsfiddle.net/KN9xx/1102/
Suppose I received an ajax call with the following data I pass to a scope variable:
$scope.people_model = {
"people":[
{
"id":"1",
"name":"Jon"
},
{
"id":"2",
"name":"Adam"
}
]
};
How would I work with the select box to iterate over the 'people' via ng-options?
<select
ng-options="p.name for name in people_model"
ng-model="people_model">
</select>
Change your select as ,
<select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
You need to access the array people inside the object people_model
DEMO
var app = angular.module('myapp', []);
app.controller("FirstCtrl", ["$scope",
function($scope) {
$scope.currentSelected = "1";
$scope.people_model = {
"people": [{
"id": "1",
"name": "Jon"
}, {
"id": "2",
"name": "Adam"
}]
};
}
]);
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="FirstCtrl">
<select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
</body>
</html>

How to call a function to renders items in a `ng-repeat` directive?

I am writing a directive to output a list of items. Those items are meant to be read from a JSON somewhere.
Now, I want to render each item accordingly to a method that would be passed to the directive. Then, in my template, I call the method, passing it the item to be rendered.
The method itself is called, but the passed item is undefined.
Where am I wrong, and how to acheive this?
You can see and play with the code here:
https://jsfiddle.net/zpntqayr/
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<drop-down-list items="data" display-item="itemToString(item)" />
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.data = [{ "Name": "Value 1", "Value": 1 }, { "Name": "Value 2", "Value": 2 }, { "Name": "Value 3", "Value": 3 }, ] ;
$scope.itemToString = function (item) {
// alert(item);
return item.Name;
};
});
myApp.directive('dropDownList', function () {
return {
restrict: 'E',
replace: true,
scope: {
items: '=',
displayItem: '&'
},
template: '<ul><li ng-repeat="item in items">{{displayItem(item)}}</li></ul>',
};
});
</script>
</body>
</html>
Just replace the code in the directive template as below:
{{displayItem(item)}}
with
{{displayItem({item: item})}}

ng-repeat not showing me value from the array

I am using ng-repeat directive but it does not showing me value. Here is my code
JS File:
var artist = angular.module('artistApp',[]);
artist.controller('artistController',['$scope',function($scope){
$scope.author =
{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham"
},
{
"name":"Jonathan G. Ferrar II",
"shortname":"Jonathan_Ferrar"
},
{
"name":"Hillary Hewitt Goldwynn-Post",
"shortname":"Hillary_Goldwynn"
}
}]);
HTML file:
<head>
<meta charset="utf-8">
<title>Angular Demo</title>
<script src="angular/angular.min.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<div ng-controller="artistController">
<ul>
<li ng-repeat="item in author">
{{item.name}}
</li>
</ul>
</div>
</body>
Where is the mistake that i m doing wrong here.
You're missing the opening bracket to the author array
$scope.author =
{
Needs to be:
$scope.author =
[{
in JS
$scope.author =
[{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham"
},
{
"name":"Jonathan G. Ferrar II",
"shortname":"Jonathan_Ferrar"
},
{
"name":"Hillary Hewitt Goldwynn-Post",
"shortname":"Hillary_Goldwynn"
}];
HTML
<li ng-repeat="item in author track by $index">
{{item.name}}
</li>
Replace the last '}' with ']'
Working Plunker
Corrected JSON:
[{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham"
},
{
"name":"Jonathan G. Ferrar II",
"shortname":"Jonathan_Ferrar"
},
{
"name":"Hillary Hewitt Goldwynn-Post",
"shortname":"Hillary_Goldwynn"
}
]

How to handle item click on list generated from ng-repeat and load next page

I have an html list generated using ng-repeat.
<div ng-repeat="product in store.products">
{{product.name}}
</div>
The data for the list is obtained from a json array in my app.js in this format:
var items = [
{
"name": "Nexus 5",
"size": "4.95 inches",
"camera": "8 megapixels"
},
{
"name": "Nexus 6",
"size": "6.0 inches",
"camera": "13 megapixels"
}
];
I want to click on the list item and go to another page showing the respective details from the same json array. How do I do that? Have been trying to access index from the list and use it to load next page, but am unsuccessful so far. I am new to angular as well as javascript. Any intermediate steps will be very helpful.
Also, notice I am handling click on the list using an anchor tag. Is this the ideal way to do it?
Please see for demo here http://plnkr.co/edit/qVEhc0KgKjklWCmqKJ4L?p=preview
HTML:
<!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.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script data-require="angular-route#1.2.16" data-semver="1.2.16" src="http://code.angularjs.org/1.2.16/angular-route.js"></script>
<script src="app.js"></script>
</head>
<body >
<div ng-view></div>
</body>
</html>
JS:
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/main', {
templateUrl: "main.html",
controller: "mainController"
}).when('/detail/:productName', {
templateUrl: "details.html",
controller: "detailsController"
}).otherwise({
redirectTo: "/main"
});
})
.controller("mainController", function($scope, dataService) {
$scope.store = {}; //.products
$scope.store.products = dataService.getProducts();
})
.controller("detailsController", function($scope, $routeParams, dataService) {
$scope.product = dataService.getProductAt($routeParams.productName);
});
angular.module("plunker").service("dataService", function(filterFilter) {
var items = [{
"name": "Nexus 5",
"size": "4.95 inches",
"camera": "8 megapixels"
}, {
"name": "Nexus 6",
"size": "6.0 inches",
"camera": "13 megapixels"
}];
this.getProducts = function() {
return items;
};
this.getProductAt = function(_name) {
this.getProducts();
return filterFilter(items, {
name: _name
})[0];
};
});
(you need details.html and main.htm template as well)

ng-select dropdown ajax/object mapping

Using angular ng-select, looking for the best practice/suggestion for linking the select drop-down with the selected option selected based on the properties of an object in scope.
The controller holds an object that (animal) that has a selected cat
The cats (options) are loaded from an Ajax call using any "promise" type angular service ($http in demo)
When the page loads, I want the selected cat to be the same as the animal.cat (would love to see easiest path to bi-directional mapping)
Here is the plunker: http://plnkr.co/edit/bMj7678djgPoJbiTRceG?p=preview
Service/Controller JS.
selectDemo = angular.module('selectDemo',[]);
selectDemo.factory("cat", ["$http", "$log", function($http, $log){
return {
query: function(runAfter){
$log.debug("Getting cats from service");
return $http.get('getCats.json');
}
}
}]);
selectDemo.controller('SelectDemoCtrl', ["$scope", "$log", "cat", function($scope, $log, Cat){
$scope.animal = {type: "Mammal", cat: {"id": 2, "name": "Simon", "breed": "Persian"}};
Cat.query().then(function(data){
cats = data.data;
$scope.cats = cats;
});
}]);
Html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="selectDemo" ng-controller="SelectDemoCtrl">
<h1>AngularJS Select Dropdown</h1>
<div id="data"></div>
<form role="form">
<select data-ng-model="animal.cat" data-ng-options="cat.name for cat in cats">
<option value="">Select a cat</option>
</select>
</form>
<p>You selected: {{ animal.cat }}</p>
</body>
</html>
JSON Response Object:
[{"id": 1, "name": "Garfield", "breed": "Tabby"},
{"id": 2, "name": "Simon", "breed": "Persian"},
{"id": 3, "name": "Twix", "breed": "Mixed"}]
Here's an updated plunk:
http://plnkr.co/edit/KTJt9602eD5Pgr1y7c9w?p=preview
The issue here is that the selected object from the ng-options needs to be reference equal to the object referenced by ng-model, hence the need to find the object in the array.

Categories

Resources