Filter separate variable in Angular - javascript

So I have some code that looks like this:
<input ng-model="search" type="text">
<td ng-repeat="key in targets">
{{ display_names[key] }}
</td>
To be more clear:
targets is a variable containing not-human readable ids such as key012
display_names is an object which has keys like: key012: "USA"
I would like to filter the display_names value from the search? Looking at the angularjs docs, I know I can filter key, but I haven't figured out how to filter display_names
Example
Here's a full example:
var TS = angular.module('myapp', []);
TS.controller('test', function($scope) {
$scope.targets = ["id_1", "id_2"];
$scope.display_names = {
"id_1": "USA",
"id_2": "Mexico"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myapp" ng-controller="test">
<input ng-model="search" placeholder="Search...">
<ul>
<li ng-repeat="key in targets">{{display_names[key]}}</li>
</ul>
</body>

<td ng-repeat="key in targets">
<span ng-if="display_names[key].indexOf(search) > -1">{{ display_names[key] }}</span>
</td>
use ng-if, or you could also use ng-show. Differences here
This way, as you write in search (which should be in $scope.search) angular will refresh the ng-repeat values to show
If you want to search it case-insensitive, you could use toLowerCase() function before using indexOf
display_names[key].toLowerCase().indexOf(search) > -1

You can't use a filter | in the html because you don't have the value you want to filter against in the array you are iterating over. Instead you can use ng-if to show/hide the elements based on the search. Something like:
<div ng-repeat="key in targets" ng-if="!search || !!display_names[key].match(search)">
{{ display_names[key] }}
</div>
The !! boolean cast is done because otherwise a new Regex object will be returned for the match which triggers a digest cycle which will return another new object and so on.
You also probably want to iterate over <tr> rather than <td>, and you need a <table> element for these elements to be allowed.
Example: http://plnkr.co/edit/qrpLKD9x4IBXowpIgnrf?p=preview
You could also write a custom filter for this, but it is a lot more work:
.filter('displayNames' function () {
return function (key, names, search) {
return !search || !!names[key].match(search);
};
});
And use it like key in targets | displayNames:display_names:search

Related

watch the value in angularjs

how to watch the array value of ng-model in angularjs i have created fiddle but does not work Please take a look and suggest.
Thanks
<div ng-app ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
<table>
<tr ng-repeat="user in profiles track by $index">
<td>
<input
type="text"
name="parktime_{{user.user_id}}"
ng-model="orderItems[user.user_id].parktime"
>
</td>
</tr>
</table>
</div>
</div>
function ParentCtrl($scope) {
}
function ChildCtrl($scope) {
$scope.parkOptions = {};
$scope.profiles = [
{user_id: '01', park_name: 'England Park'},
{user_id: '02', park_name: 'France Park'}
];
$scope.orderItems = {};
$scope.orderItems.parktime = "Test";
$scope.$watch('orderItems[profiles.user_id].parktime', function(newVal, oldVal){
console.log(newVal);
})
}
http://jsfiddle.net/w5vskLfc/59/
I suggest you use ng-change instead. You can't use watch this way, it is to watch a single property instead.
I've also updated your model to use ng-init. This is something you should be careful with using, but in your case, you need to have an key defined at each position of your orderItems object. If you will always statically assign these, I recommend iterating through them once and creating a key that way instead.
HTML
<input type="text" name="parktime_{{user.user_id}}"
ng-init="orderItems[user.user_id] = {}"
ng-model="orderItems[user.user_id].parktime"
ng-change="onChange(user.user_id)">
JS
$scope.onChange = function(items) {
console.log(items);
}
You are trying to access indexes which does not exist. profiles is an array of objects and I don't think there is anything available on profiles.user_id index. Also, I don't think orderItems[profiles.user_id] will work as that index also doesn't exist.

I am unable to figure out how filter will work when we are using "keyword.name" in ng-model and in filter we are using "filter: keyword"

I am new to angular js. I am unable to figure out how filter will work only on the name in object not on the phone key in the object.As if we use only keyword in ng-model it will filter both name and phone in the object defined in the scope while in the case of the keyword.name it will filter out only name.
<script>
var app = angular.module("app" , []);
app.controller("controller" ,['$scope' , function($scope){
$scope.answer = 1+2;
$scope.object=[
{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]
}]);
</script>
<div ng-app = "app" ng-controller="controller" >
<input type="text" ng-model="keyword.name" />
<table>
<thead>
<th>Name</th>
<th>Phone</th>
</thead>
<tr ng-repeat = "item in object | filter: keyword" >
<td> {{item.name}} </td>
<td> {{item.phone}} </td>
</tr>
</table>
</div>
</body>
If you filter based only on keyword which is your ng-model, then angular by default adds a special property name that matches against any property. By default it is $. So technically filtering based on keyword as ng-model is same as filtering based on keyword.$. But if you append a property to the keyword it will overide angular's default special property name and filters based on your new key value.
https://docs.angularjs.org/api/ng/filter/filter
Here you are passing object(keyword) as an expression in filter to select from the array. you have declared only one property of object keyword.name. You have to see filter:keyword as filter:{name:"this value will be item.name"}. So this return the array items with a name only.
for example of if you had ng-model="keyword.dance". then have to see filter:keyword as filter:{dance:"this value will be item.dance"}. As here their will be no match so you will get blank result.

Filter Number in an angular object using limitto

I am using a angularjs filter method on an repeated array of items and trying to filter numbers with a limitTo filter. The result is not getting applied to the repeat in the DOM.
Here is the html
<div ng-controller="demo as d">
<input type="text" ng-model="d.test" ng-change="d.filterthis(d.test)"><br>
<div ng-repeat="item in d.items | limitTo:d.limitto track by $index">
<span ng-show="!item.show">{{item.myno}}</span> -
<span ng-show="!item.show">{{$index}} - {{item.mystr}}</span><br>
</div>
</div>
App.js filter function withing angularjs
this.filterthis = function(filter){
that.items.map(function(filter){
return function(obj){
obj.show=true;
if(obj.myno.toString().indexOf(filter) >-1){
console.log(obj);
obj.show=false;
}
return obj;
}
}(filter));
};
Items is a array like this
this.items = [{
show:false,
myno:10,
mystr:"test1"
}];
http://plnkr.co/edit/bTdlTpSeZuPyGpolXLEG
Having "show" as a key on your items, doesnt remove it from the ng-repeat, and so the limitTo filter will still return the items. Instead you should leverage the filter filter in the repeat like so
<input type="text" ng-model="d.search"><br>
<div ng-repeat="item in d.items | filter:{myno:d.search} | limitTo:d.limitto track by $index">
<span>{{item.myno}}</span> -
<span>{{$index}} - {{item.mystr}}</span><br>
</div>
Note that order is important here, if you limitTo and then filter you are only filtering the limit'ed result. You can change the key upon which you filter by changing {myno:d.search} to a different key, alternatively if you want to search the whole object, simply use d.search.
Updated Plunker

adding an array property to object in angular js

I have an object called user:
It has properties like user.name, user.age e.tc.
Now, I need to add an array to user object called subjects via ng-model.
This is what i did inside of ng-repeat:
<input type="text" ng-model="user.subjectname[$index]"
name="subject" ng-required="true" placeholder="Enter a subject name">
and when I do console.log(user.subjectname), it looks like this:
Now, after this, I wanted to do something like this:
<div ng-repeat="data in user.sujects">
<td>{{data}} </td>
</div>
But it does not work.
Try2:
In my my service that is called from controller, I tried this,
if(dataArray== null)
var dataArray=[];
console.log("scop.user.subjectname...................." + user.subjectname);
for(var i in user.subjectname)
{ dataArray.push(user.subjectname[i])
}
user.data=dataArray;
so, now if I do,
<div ng-repeat="data in user.data">
<td>{{data}} </td>
</div>
I still get nothing.
Can I get some direction to deal with this?
Like I told you in your previous question, and showcased in a jsbin.
You need to use the (key, val) in object syntax to get those values out of user.subjectname
ng-repeat="(key, val) in user.subjectname" ng-bind="val"
If you need to transform this object into an array:
$scope.arr = [];
Object.keys(user.subjectname).forEach(function (key) {
arr.push(user.subjectname[key]);
});
Then if you need to output that
ng-repeat="a in arr" ng-bind="a"
edit: after further explanation from you, I'm assuming this jsBin highlights something close to what you are after.

How to handle array in angular js/HTML

I'm using a Web API to display values in HTML via Angular.
I have 4 attributes: Id, MovieName, Date and Cast. Cast is an array. I don't know how to handle the Cast attribute.
Controller.js
app.controller('MyController', function ($scope, MyService) {
$scope.getemploy = function () {
var promise = MyService.getMovies();
promise.then(function (pl) {
$scope.Movies= pl.data
},
function (error) {
$log.error('Some Prob', error);
});
}
GetMovies()--> will bring movie details(Cast attribute will have male, female lead names in the array).
HTML File :
<tr ng-repeat="mov in Movies">
<td>{{mov.Id}}</td>
<td>{{mov.MovieName}}</td>
<td>{{mov.Date}}</td>
<td>{{mov.Cast}}</td>
</tr>
But it's not working. I think I'll need some other way to handle Cast attributes, whether in html or angular.
My Json output for your reference:
[
{
"_movieId": 1,
"_moviename": "Olympus Has Fallen",
"_releaseDate": 2013,
"_cast": [
"Gerard Butler",
"Dylan McDermott",
"Aaron Eckhart",
"Angela Bassett"
]
}
Can anyone please help?
But its not working....
Because according to posted JSON your receive, HTML should be with different keys. Try this:
<tr ng-repeat="mov in Movies">
<td>{{mov._movieId}}</td>
<td>{{mov._moviename}}</td>
<td>{{mov._releaseDate}}</td>
<td>{{mov._cast.join(', ')}}</td>
</tr>
I used simple join method of array to render comma separated list of actors. If you need something more specific, you will need to make use of one more ngRepeat on mov._cast array (see Danny's answer).
I'm not sure what you mean by the Cast is not working, but I'm guessing it's just showing the JSON object in the HTML? You could show all the cast members in a list doing something like:
<tr ng-repeat="mov in Movies">
<td>{{mov.Id}}</td>
<td>{{mov.MovieName}}</td>
<td>{{mov.Date}}</td>
<td>
<ul>
<li ng-repeat="member in mov.Cast">{{ member }}</li>
</ul>
</td>
</tr>

Categories

Resources