I am having the following array that i want to manipulate in DOM using Angularjs with some filters
$scope.urls = [{
path: 'http://a.com/index'
}, {
path: 'http://a.com/home'
}, {
path: 'http://a.com/etc'
}, {
path: 'http://a.com/all'
}];
I had tried to substring the path using filters but it is not working.
Fiddle Demo
Any help is great.
Try this one:
HTML
<div ng-controller = "fessCntrl">
<h1>Only path without domain name:</h1>
<ul>
<li ng-repeat="url in urls | myCustomFilter">{{url.path}}</li>
</ul>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.urls = [{
path: 'http://a.com/index'
}, {
path: 'http://a.com/home'
}, {
path: 'http://a.com/etc'
}, {
path: 'http://a.com/all'
}];
$scope.otherCondition = true;
});
fessmodule.$inject = ['$scope'];
fessmodule.filter('myCustomFilter', function() {
return function( urls) {
var filtered = [];
angular.forEach(urls, function(url) {
filtered.push( {path:url.path.substring("http://a.com".length, url.path.length)});
});
return filtered;
};
});
Demo Fiddle
As a side note:
Try to write filters out of controller.
AngularJS v 1.4.5 supports a standard "limitTo" filter for arrays(including string) with parameters length and offset:
<div ng-controller = "SampleController">
<h1>Result of substring equivalent filter:</h1>
<ul>
<li ng-repeat="url in urls">{{url.path | limitTo:5:12}}</li>
</ul>
</div>
Note: This solution fails in case of dynamic domain length("http://a.com" static length of 12).
Note 2: Increase length to the maximum resulting length of path(Max is "index" having length of 5).
Overview of all filters supported by AngularJS out of the box.
Related
can someone help me to bite it?
Problem is, that I have res with server string, array of orders
Array
[ Object, Object, Object ]
And wants to display the item's value from all objects one by one
example:
order 1 [
DELL
ziemniaki
Wisnie
111111111 ]
order 2 [
Wisnie
Ziemniaki
]
Controller:
$scope.ListOfOrders = function () {
return ApiService.cart.list($scope.user).then(function (resp) {
$scope.orders = JSON.parse(resp[0].order);
console.log(resp)
});
}
in {{orders}} is
> [{"_id":"596f39515156f6178cbf3721","order":"[{\"item\":\"DELL\",\"quantity
> \":6,\"price\":144},{\"item\":\"ziemniaki\",\"quantity\":3,\"price\":3131},
> {\"item\":\"Wisnie\",\"quantity\":1,\"price\":31},{\"item\":\"111111111\",\"quantity\":1,\"price\":13}]","price":10301,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-19T10:49:53.061Z","updated":"2017-07-19T10:49:53.061Z"},{"_id":"597085de1d3e9722385773a8","order":"[{\"item\":\"ziemniaki\",\"quantity\":2,\"price\":3131},{\"item\":\"Wisnie\",\"quantity\":5,\"price\":31}]","price":6417,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-20T10:28:46.591Z","updated":"2017-07-20T10:28:46.591Z"},{"_id":"597086e41d3e9722385773a9","order":"[{\"item\":\"ziemniaki\",\"quantity\":2,\"price\":3131},{\"item\":\"Wisnie\",\"quantity\":5,\"price\":31}]","price":6417,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-20T10:33:08.444Z","updated":"2017-07-20T10:33:08.444Z"}]
you can modify the data as per your requirement -
like you can do this.
var newOrders=[]
angular.forEach(orders,function(value,key){
var obj={};
obj.Ordername="Order"+key;
obj.values=[];
angular.forEach((value.order),function(v,k){
obj.values.push(v.item);
})
newOrders.push(obj);
})
Now this newOrder can be used as you want.
Hope it will help you.
You can filter the item from response to display -
app.controller('orderCtrl', ['$scope', 'ApiService', '$filter',
function(s, ApiService, $filter) {
s.newOrders = [];
//Function to get the order response
s.ListOfOrders = function () {
return ApiService.cart.list(s.user).then(function (resp) {
s.orders = JSON.parse(resp[0].order);
//Now everything in orders
s.orders.forEach(function(o) {
s.newOrders.orderName="Order"+key;
s.newOrders.items = o.filter(function(r) { return r.item })
console.log(s.newOrders )
})
});
}
}])
//In html template
<div ng-repeat="order in newOrders">
<span>order.orderName</span>
<div ng-repeat="item in order.items">
{{item}}
</div>
</div>
I'm trying to ignore a property called title in my angular filter. I have a dataset like the below example:
const data = [
{
title: 'Title 1'
groups: [
{...},
{...},
{...}
]
},
{
title: 'Title 2'
groups: [
{...},
{...},
{...}
]
},
{
title: 'Title 3'
groups: [
{...},
{...},
{...}
]
}
];
And i'm using the ng-repeat with filter to iterate over the objects, and other loop to iterate over the groups:
<input ng-model="search">
<div ng-repeat="item in data | filter:search">
<h1>{{item.title}}</h1>
<ul>
<li ng-repeat="group in item.group | filter:search">
<span>{{group.something}}</span>
</li>
</ul>
</div>
Is working fine, but now i would like to ignore the title in the search. I did try several things, like: filter:search:item.title (in the first ng-repeat), or remove the first filter:search, but all tries failed. What i'm missing? Do i need a custom search or something like that?
Thank you.
You can specifically enter properties you want to filter and leave out title:
<li ng-repeat="group in item.groups | filter: { something: search }">
The above code will only filter based on the something property.
More answers and explanations here: AngularJS filter only on certain objects
If you type and no filtering the title property, just remove the first filter. This way when you type the li's isnt match will hide, but their h1's will stay the same place.
You should create custom filter, where you can specify which property should be excluded(ignore parameter) from consideration:
angular.module('app', []).controller('MyController', ['$scope', function($scope) {
$scope.data = [
{name:"Tom", title:'London'},
{name:"Max", title:'Moscow'},
{name:"Henry", title:'NY'},
{name:"Paul", title:'NY'},
{name:"Sam", title:'Paris'}
];
}]).filter('myfilter',function(){
return function(input, search, ignore){
if(!search)
return input;
var result = [];
for(var item of input)
for(var prop in item)
if(prop != ignore && item[prop].indexOf(search) != -1)
{
result.push(item) ;
break;
}
return result;
}
});
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MyController">
search: <input type='text' ng-model='search' ng-init='search="a"'/>
ignore: <input type='text' ng-model='ignore' ng-init='ignore="title"'/>
<ul>
<li ng-repeat='item in data | myfilter: search: ignore'>
{{item.name}} {{item.title}}
</li>
</ul>
</div>
</body>
I'm new to AngularJS, I was trying a code with ng-repeat but got stuck because I need to pass the angular expression to a function but it is not working below is my code:
HTML code
<div ng-controller="Profile as pro">
<ul class="nav nav-tabs">
<li ng-repeat="tabs in tabArray"
ng-class="{active: pro.tab==1}"
ng-click=" pro.setTab({{tabs.value}})">
{{tabs.name}}
</li>
</ul>
<div>
Controller code
controller.controller('Profile', ['$scope',function ($scope) {
$scope.tabArray = [
{name:"Profile","value":1},
{name:"Education","value":2},
{name:"Work","value":3},
{name:"About","value":4}
];
this.tab=1;
this.setTab = function(tabSelected){
this.tab=tabSelected;
};
}]);
Use ng-click ="pro.setTab(tabs.value)"
Only proble in your code is in following line:
ng-click=" pro.setTab({{tabs.value}})" // don't use {{ and }} thing here, it is not needed
Following code is fixed version:
ng-click="pro.setTab(tabs.value)" // only {{ and }} are removed and it works well
Happy Helping!
There were some mistakes in your existing code ->
Since you are making use of ControllerAs syntax, you should refer with the variable used for the controller, with all the variables referenced in the view.
Here, in the ng-repeat of your model refer by pro.tabArray.
There is no need to pass the parameters in AngularExpressions, at the time of function/method call.
So, make use of ng-click="pro.setTab(tabs.value)", without the expressions.
HTML Code:
<li ng-repeat="tabs in pro.tabArray" ng-class="{'active': pro.tab==1}" ng-click="pro.setTab(tabs.value)">{{tabs.name}}</li>
In your JS too, you have referred some varibales with $scope and some with this. Be consistent with your code and do not mix it.
JS Code:
var app = angular.module('app', []);
app.controller('Profile', function ($scope) {
this.tabArray = [
{ name: "Profile", "value": 1 },
{ name: "Education", "value": 2 },
{ name: "Work", "value": 3 },
{ name: "About", "value": 4 }
];
this.tab = 1;
this.setTab = function (tabSelected) {
this.tab = tabSelected;
};
$scope = this;
});
I am fairly new to angular and am working with a client that wants a dropdown allowing users to select their neighborhood which is then saved in a cookie to load upon return. I am able to save cookie but am having trouble getting dropdown selected neighborhood to load proper template.
Here is the html:
<select id="mNeighborhood" ng-model="mNeighborhood" ng-options="neighborhood.id as neighborhood.name for neighborhood in neighborhoods" ng-change="saveCookie()"></select>
And then, I have added the following in html:
<div ng-view=""></div>
Here is the app.js code:
var app = angular.module('uSarasota', ['ngCookies', 'ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
template: '<div><h1 style="margin: 200px;">This is our main page</h1></div>'
})
.when('/downtown', {
templateUrl: "templates/downtown.html"
})
.otherwise({
template: '<div><h1 style="margin: 200px;""><strong>NOTHING TO SEE HERE</strong></h1></div>'
})
});
//Select Neighborhood
app.controller('myNeighborhood', ['$scope', '$cookies', function($scope, $cookies) {
$scope.neighborhoods = [{
name: "My Neighborhood",
id: 0
}, {
name: "All of Sarasota",
id: 1
}, {
name: "Downtown",
url: "/downtown",
id: 2,
}, {
name: "North Sarasota",
id: 3
}, {
name: "Lakewood Ranch",
id: 4
}, {
name: "Longboat Key",
id: 5
}, {
name: "St. Armands Circle",
id: 6
}, {
name: "Southside Village",
id: 7
}, {
name: "Siesta Key",
id: 8
}, {
name: "Gulf Gate",
id: 9
}];
//Set Cookie so when user returns to site, it will be on their neighborhood
$scope.mNeighborhood = parseInt($cookies.get('sNeighborhood')) || 0;
$scope.saveCookie = function() {
$cookies.put('sNeighborhood', $scope.mNeighborhood);
};
}]);
This all works fine to save and load user selection, but am having trouble finding solution to get template based on selection. So, should I add url to the array for each neighborhood and if so, how do I get the link?
Basically you need to change the URL programatically on selection of dropdown. For achieving this thing you need to first change you ng-options to return object on selection. And then using that object get url property from it to load particular template.
Markup
<select id="mNeighborhood"
ng-model="mNeighborhood"
ng-options="neighborhood.name for neighborhood in neighborhoods"
ng-change="saveCookie()">
</select>
Code
$scope.saveCookie = function() {
var mNeighborhood = $scope.mNeighborhood;
$cookies.put('sNeighborhood', mNeighborhood.id);
//do add $location dependency in controller function before using it.
$location.path(mNeighborhood.url);
};
Update
On initial Load the value should be set as object as per new implementation.
$scope.mNeighborhood = {}; //at the starting of controller
//the other code as is
//below code will get the object from the neighborhoods array.
$scope.mNeighborhood = $filter('filter')($scope.neighborhoods, parseInt($cookies.get('sNeighborhood')) || 0, true)[0];
$scope.saveCookie = function() {
var mNeighborhood = $scope.mNeighborhood;
$cookies.put('sNeighborhood', mNeighborhood.id);
//do add $location dependency in controller function before using it.
$location.path(mNeighborhood.url);
};
I am accessing the instagram API to fetch photos that a specific user has liked and the first comment that said user has posted. However I only want to retrieve the URL from the text for example, the user tellasaur first comment is:
"text":"Check out this link http://www.domain.com",
I only want to retrieve http://www.domain.com. Here is my code so far:
So I want to apply a regex on this part {{p.comments.data|getFirstCommentFrom:'tellasaur'}}"
but not sure how.
JS
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":"Check out this link http://www.domain.com",
"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"
}
]
}
}
]
});
HTML NG-LOOP
<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></p>
</li>
</div>
See this answer on how to regex match urls in text, your solution is in there somewhere