I have a multi check box application which requires me to have multiple filters. I have been unable to use multiple filters even if I try to hard code an array to filter on. Here is an example I have created to try to make this work.
Working Example
HTML MARKUP:
<body ng-app="app">
<div ng-controller="MainCtrl">
<div ng-repeat="item in data.sessions | IndustryFilter : data.sessions.industry ">
{{item.id}}
</div>
</div>
Javascript
var app = angular.module("app", [])
.controller("MainCtrl", function ($scope, MatchedFilterList) {
$scope.data = {"sessions": [{
"id": "a093000000Vhzg7AAB",
"industry": ["Automovtive"],
"sessionName": "Keynote",
},
{
"id": "a093000000zg7AAB",
"industry": ["Automovtive", "Retail"],
"sessionName": "Keynote2",
},
{
"id": "a093er000f00zg7AAB",
"industry": ["Automovtive", "Retail", "Consumer Goods"],
"sessionName": "Keynote3",
}
]};
}).filter("IndustryFilter", function (MatchedFilterList) {
return function () {
var filtered = [];
angular.forEach(MatchedFilterList.industry, function (item) {
filtered.push(item);
});
console.log("Filter: Filter " + filtered)
return filtered;
};
})
.factory("MatchedFilterList", function(){
var matchedFilterList = {};
matchedFilterList.industry = {
"Automotive": "Automotive",
"Retail" : "Retail"
};
return matchedFilterList;
});
Related
Within angular I have a filtered list of people that takes the filter criteria from a predicate function. I want to watch a variable of the filtered list (called filteredPeople) every time the filtered list changes. But I am unable to see when that variable changes.
My code is below:
HTML:
<ul>
<li ng-repeat="person in ($ctrl.filteredPeople = ($ctrl.people | filter: $ctrl.filter))">
...
</li>
</ul>
JS:
controller: ['$scope',
function ($scope) {
var $ctrl = this;
$ctrl.people = {...}
$ctrl.filteredPeople = [];
$scope.$watch($ctrl.filteredPeople, function () {
console.log("called"); //not being called
});
$ctrl.filter = function (p) {
//custom filter function for each item in the array of people
}
}]
I can answer any questions of provide more code if needed
angular.module('app', []).controller('ctrl', function($scope) {
var vm = this;
vm.items = [
{ name: 'Sam' },
{ name: 'Max' },
{ name: 'Tom' },
{ name: 'Henry' },
{ name: 'Jack' },
{ name: 'Kate' }
]
var counter = 1;
$scope.$watchCollection('vm.filtered', function(){
console.log('Changed' + counter++);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl as vm'>
<input type='text' ng-model='vm.filter' />
<ul>
<li ng-repeat='item in vm.filtered = (vm.items | filter : vm.filter)'>{{item}}</li>
</ul>
</div>
I'm doing a shopping cart with AngularJs, but I'm having trouble adding products to the shopping cart.
I think error is on my Controller:
My data.json:
{
"items": [
{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}
]
}
my controller.js :
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function(data) {
angular.forEach(data.items, function(item, index) {
$scope.products.push(item.product);
});
});
}
$scope.carts=[];
$scope.add_cart = function(product){
if(product){
$scope.carts.push({ p_name: product.name, p_valor:product.price.value,);
}
}
$scope.total = 0;
$scope.setTotals = function(cart){
if(cart){
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function(cart){
if(cart){
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
]);
my html:
<body ng-controller="ListCtrl" ng-app="list">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "add_cart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "remove_cart(cart)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
</body>
I need the button add to cart to work correctly, bringing the product name and the value of the product. I also need it to bring the total value and also need to remove the product when clicking button remove cart.
Ty for Help guys!
your controller.js file contain some syntax error. please check for any typo or syntax error in code before you throw your code into stackoverflow 's basket. anyway,
there are some point you need to remember when code.
camelCase is recommended in javascript. as per conventions
each function should dedicated to perform a specific task (personal opinion)
it's good to follow styleguide angularjs &
javascript
$scope, and $watch is for data binding, so you can use data in template or in other scopes like directive. data-binding is great and primary selling point of AngularJs, but it has some drawbacks.
and power comes with great responsibility. :wink
please have a look, here is a working live demo of your code.
var app = angular.module("list", []);
ListController.$inject = ["$scope", "$http"];
app.controller("ListCtrl", ListController);
function ListController($scope, $http) {
function onLoad() {
$scope.products = [];
$scope.carts = [];
$scope.total = 0;
// getProducts();
demoData();
}
onLoad();
$scope.addCart = addCart;
$scope.getTotals = getTotals;
$scope.removeCart = removeCart;
// hould remove when using in prod
function demoData() {
var data = {
"items": [{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}]
}
parseProducts(data.items);
}
function getProducts() {
$http.get('data.json')
.success(function(data) { parseProducts(data.items) })
}
function parseProducts(items) {
angular.forEach(items, function(item, index) {
$scope.products.push(item.product);
});
}
function addCart(product){
if(product){
$scope.carts.push({
p_name: product.name,
p_price:product.price.value
});
}
}
function getTotals(){
var initialValue = 0;
$scope.total = $scope.carts.reduce((x,y) => x + y["p_price"], initialValue);
}
function removeCart(i){
$scope.carts.splice(i, 1);
getTotals();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="list" ng-controller="ListCtrl">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "addCart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat="cart in carts track by $index" ng-init = "getTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "removeCart($index)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
<button ng-click="getTotals()">get totals</button>
</body>
I found some Syntax error
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http",
function ($scope, $http) {
$scope.products = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function (data) {
angular.forEach(data.items, function (item, index) {
$scope.products.push(item.product);
});
});
$scope.carts = [];
$scope.add_cart = function (product) {
if (product) {
$scope.carts.push({
p_name: product.name,
p_valor: product.price.value,
}); //Here syntax err
}
}
$scope.total = 0;
$scope.setTotals = function (cart) {
if (cart) {
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function (cart) {
if (cart) {
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
} //Here syntax err
]);
i'm developing an app where i should retreive from the server a JSON array through the http.get method.
The structure of the array is this:
[{
"day": "17/11/2016",
"time": "09:45"
}, {
"day": "17/11/2016",
"time": "16:50"
}, {
"day": "18/11/2016",
"time": "11:25"
}, {
"day": "18/11/2016",
"time": "12:30"
}, {
"day": "21/11/2016",
"time": "16:10"
}, {
"day": "21/11/2016",
"time": "17:25"
}]
From this array i should create a form with two selects where in the first i've days (for example 17/11/2016, 18/11/2016, 21/11/2016) and in the second i should have times "belonging" at days (for example 09:45, 16:50 OR 11:25, 12:30 OR 16:10, 17:25).
I think that i've found the solution at this problem but when i tried to run the project selects are always empty but the console tell me no errors.
This is my code,
HTML:
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div class="form-group">
<label>Event Date</label>
<select ng-options="event as event.date for event in ctrl.data.events" ng-model="ctrl.event">
<option value="">Select</option>
</select>
</div>
<div class="form-group">
<label>Event Time</label>
<select ng-options="schedule as schedule.time for schedule in ctrl.data.schedules | filter: { date: ctrl.event.date}" ng-model="ctrl.schedule" ng-disabled="!ctrl.event">
<option value="">Select</option>
</select>
</div>
</div>
</div>
</body>
</html>
JS:
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService'];
function DefaultController(dataService) {
var vm = this;
getEvents();
function getEvents() {
return dataService.getEvents()
.then(function (data) {
vm.data = data;
return vm.data;
});
}
}
dataService.$inject = ['$http'];
function dataService($http) {
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json; charset=utf-8" && angular.isString(data)) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
return result;
} else {
return data;
}
}
};
return $http.get('events.json', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
Can someone help me?
Than'ks
i have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj
function simpleController($scope) {
$scope.data = {
"results1": [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] ,
"results2": [ { "id": 1, "name": "Test2" }, { "id": 2, "name": "Beispiel2" }, { "id": 3, "name": "Sample2" } ]
}
;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app>
<body ng-controller="simpleController">
<div data-ng-repeat="results in data">
<div data-ng-repeat="result in results">>
{{result.name}}</br>
</div>
</div>
</body>
</html>
Have Fun..!!!
In your controller:
$scope.all_results = data.results1.concat(data.results2);
In your view
<whatever ng-repeat="item in all_results">{{ item.id }} - {{ item.name }}</whatever>
You could work with an extra <div> with ng-repeat attribute in your HTML where in my example results is your data.
<div>
<div ng-repeat="result in results">
<div ng-repeat="item in result">{{item.name}}</div>
</div>
</div>
ok this work ... i have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj
I'd like to retrieve specific data within a JSON file within an ng-repeat loop, My code is as follows thus far, and it works correctly bringing in the correct low resolution url of the image. I want to display the first comment corresponding to this image from a specific user below it in the <p> tag, ie I want the the first "text" value always from the username "tellasaur". Not sure how to bring that in, could I have some help? thanks!
NG-REPEAT LOOP
<li ng-repeat="p in pics">
<img ng-src="{{p.images.low_resolution.url}}" />
<p></p>
</li>
CONTROLLER
app.controller('ShowImages', function($scope, InstagramAPI){
$scope.layout = 'grid';
$scope.data = {};
$scope.pics = [];
InstagramAPI.fetchPhotos(function(data){
$scope.pics = data;
console.log(data)
});
});
JSON
"images":{
"low_resolution":{
"url":"https:\/\/scontent.cdninstagram.com\/hphotos-xaf1\/t51.2885-15\/s320x320\/e15\/11243658_841091872640638_1858051687_n.jpg",
"width":320,
"height":320
},
},
"comments":{
"count":38,
"data":[
{
"created_time":"1436314585",
"text":"Living on a lake #amarie4107",
"from":{
"username":"tellasaur",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/11142181_1606991566225969_1204610350_a.jpg",
"id":"174270894",
"full_name":"kristella"
},
"id":"1024203434844916571"
},
{
"created_time":"1436317671",
"text":"Wow",
"from":{
"username":"sbcarol2002",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/10707061_359756607505353_826681437_a.jpg",
"id":"1280059782",
"full_name":"Susan Long"
},
"id":"1024229322726738700"
},
{
"created_time":"1436320519",
"text":"\ud83d\udc93 dreamyy",
"from":{
"username":"veekster",
"profile_picture":"https:\/\/igcdn-photos-h-a.akamaihd.net\/hphotos-ak-xtf1\/t51.2885-19\/11117059_1743047859255223_204225114_a.jpg",
"id":"31179150",
"full_name":"Victoria Wright"
},
"id":"1024253210688915485"
}
]
}
Here's one way to do it using a filter.
angular.module('app',[])
.filter('getFirstCommentFrom',function(){
return function(arr, user){
for(var i=0;i<arr.length;i++)
{
if(arr[i].from.username==user)
return arr[i].text;
}
return '';
}
})
.controller('TestCtrl', function($scope){
$scope.pics = [
{ "images":{
"low_resolution":{
"url":"https:\/\/scontent.cdninstagram.com\/hphotos-xaf1\/t51.2885-15\/s320x320\/e15\/11243658_841091872640638_1858051687_n.jpg",
"width":320,
"height":320
},
},
"comments":{
"count":38,
"data":[
{
"created_time":"1436314585",
"text":"Living on a lake #amarie4107",
"from":{
"username":"tellasaur",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/11142181_1606991566225969_1204610350_a.jpg",
"id":"174270894",
"full_name":"kristella"
},
"id":"1024203434844916571"
},
{
"created_time":"1436317671",
"text":"Wow",
"from":{
"username":"sbcarol2002",
"profile_picture":"https:\/\/igcdn-photos-b-a.akamaihd.net\/hphotos-ak-xfp1\/t51.2885-19\/10707061_359756607505353_826681437_a.jpg",
"id":"1280059782",
"full_name":"Susan Long"
},
"id":"1024229322726738700"
},
{
"created_time":"1436320519",
"text":"\ud83d\udc93 dreamyy",
"from":{
"username":"veekster",
"profile_picture":"https:\/\/igcdn-photos-h-a.akamaihd.net\/hphotos-ak-xtf1\/t51.2885-19\/11117059_1743047859255223_204225114_a.jpg",
"id":"31179150",
"full_name":"Victoria Wright"
},
"id":"1024253210688915485"
}
]
}
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app" ng-controller="TestCtrl">
<li ng-repeat="p in pics">
<img ng-src="{{p.images.low_resolution.url}}" />
{{p.comments.data|getFirstCommentFrom:'tellasaur'}}
<p></p>
</li>
</div>