Accessing objects in Angularjs - javascript

Is it possible to get age object's value with the name object on following mentioned AngularJS expression:
{{{name: 'Jhon', age: '15' }.name}}

You can do something like below:
<div>
Name = {{ {name: 'Jhon', age: '15' }.name | json }}
</div>
<div>
Age = {{ {name: 'Jhon', age: '15' }.age | json }}
</div>
Have a look at the demo.

Yes, but with a slight modification Eg.
({key : 1}).key
But you cannot use this object elsewhere. So there is no point in creating such objects unless you are referring via a variable.

Related

Vue - Loop through an array with nested objects

I'm fetching a list that I'm trying to loop through that has an object inside. I'm using vue and the array looks like this:
companies: [
name: "company1"
id: 1
type: "finance"
additionalData: "{"funder":"blabla","idType":5,"number":"2"}"
]
My problem is accessing the different ones inside the additionalData.
This is how far I've come:
<div
v-for="(company, idx) in companies"
:key="idx"
>
<p class="font-weight-bold text-h6"> {{ company.name }} </p>
<p class="font-weight-bold"> {{ company.additionalData.funder }} </p>
</div>
This doesn't work and I've tried a loop inside the loop aswell. When I only print out {{ company.additionalData }} I get the whole object. Can it have something to do with that the object is inside a string? Could I do a computed or something to figure this out or? :)
It looks like additionalData is a string containing JSON, so try converting the string to an object. Something like this should work:
<p class="font-weight-bold"> {{ JSON.parse(company.additionalData).funder }} </p>
Yes, you're right, you can't access json properties with dot notation in html. You can fix that with JSON.parse, which will turn your JSON object into a JavaScript object that you can access the properties of in your template.
companies: {
name: "company1"
id: 1
type: "finance"
additionalData: JSON.parse("{"funder":"blabla","idType":5,"number":"2"}")
}
Syntax problem
companies: [
name: "company1"
id: 1
type: "finance"
additionalData: {
"funder": "blabla",
"idType": 5,
"number":"2"
}
]

AngularJS filter as selector from array

I'm having two array in my scope: employees and cars. Every employee has a carId which matches a car out of the cars-array.
Employee looks like
[{'id': 1, 'name': 'John', 'carId': 1}]
Car like
[{'id': 1, 'color': 'red'}]
Now I have an ng-repeat and would like to output the color of the car directly with an filter:
{{ employee.carId | selectFromCars:$scope.cars }}
I don't know how to get access to the cars array inside the filter. Is this even possible or should I inject the car into the employee after loading and then just use following?
{{ employee.car.color }}
you can make your own custom filter and just add it the end of your controller like so:
.filter('empCarFilter', function() {
return function(carId, cars) {
// you can access $scope.cars here, for example...
angular.forEach(cars,function(value){
if (value.id === carId) {
return value.color;
}
// etc...etc...
})
}
The above method is under the assumption that you are passing employee.carId into the filter. But, not sure how useful this would be for you, but you can pass the whole object to the filter as well and not just one key with:
{{ employee | empCarFilter }}
Here is also a pretty good reference for custom filters:
https://scotch.io/tutorials/building-custom-angularjs-filters

AngularJS dropdown not showing selected value

Am facing problem in displaying selected value in angular dropdown.
it works when i give like this
$scope.selectedItem = $scope.items[1];
not working, if i give directly that value
$scope.selectedItem = { name: 'two', age: 27 };
HTML:
<html ng-app="app">
<body>
<div ng-controller="Test">
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
</div>
</body>
</html>
JS:
var app = angular.module('app',[]);
app.controller('Test',function($scope){
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
$scope.selectedItem = $scope.items[1];
});
CODEPEN:
http://codepen.io/anon/pen/zxXpmR
SOLUTION:
Thank you samir-das. I fixed as per your suggestion.
var choosen_value = { name: 'two', age: 27 };
angular.forEach($scope.items, function(item){
if(angular.equals(choosen_value, item)){
$scope.selectedItem = item;
}
});
As explained in the other answers, while the two objects may have the same properties and values, they are two different objects so angular doesn't consider them to be equal.
You can however use the track by expression in ng-options to specify a property which will decide equality:
ng-options="item.name for item in items track by item.name"
http://codepen.io/anon/pen/WbWMrp
Well, because
$scope.items[1] and { name: 'two', age: 27 } is totally different thing.
{ name: 'two', age: 27 } is a totally different object whereas $scope.items[1] is part of the object $scope.items
When you put something in the template using {{}}, angular add it in its watcher list.
SO when angular put it in the watch list, it was an object (i.e. { name: 'two', age: 27 } ) that is different than $scope.items.
selectedItem is attached with the object that you set in the controller. In summary while dirty checking, angular will checks selectedItem against { name: 'two', age: 27 } NOT against $scope.items
Hope you understand what I mean
This is not an Angular feature/issue, it is a consequence of how object equality works in Javascript. This article does a fairly good job in explaining what is going on in a pretty concise way and gives some examples. Check out the source of lodash's isEqual method (it will take you to the definition of baseIsEqualDeep eventually) to see how what you are trying to achieve can be done in pure JS.
In any case, I do not think there is an easy way to achieve this in Angular, you would have to re-write the way ng-options works and you probably do not want to go there...
In angular, Arrays and objects are passed by reference while strings, numbers and booleans are passed by value. So, angular interprets $scope.items[1] and { name: 'two', age: 27 } as two different objects. That's why your binding fails when you do $scope.selectedItem = { name: 'two', age: 27 }; directly and find it in '$scope.items'.

Reference a string filter from object value

I am trying to apply a filter to the output of an angular ng-repeat. Here's an example of the data:
{name: "followers", label: "Followers", filter:"number:0"},
{name: "following", label: "Following",filter:"number:0"},
{name: "mediaCount", label: "Media Count",filter:"number:0"}
The display of things looks like this:
<span ng-repeat="item in rows">
<div class="col col-gh-4"><label>{{item.label}}</label></div>
<div class="col col-gh-2" ng-bind="item.value ? (item.value|{{item.filter}}) : '-'"></div>
I am trying to apply the filter in this case "number:0" as defined in the data object at display-time using something like: item.value|{{item.filter}} or item.value|item.filter
Both of those attempts don't work, any advice on how to reference the filter from the object value? Is it possible?
Thanks for any suggestions!

AngularJS: Bind to all object properties?

I have a Model that takes an object that could contain any set of properties.
I am wondering if I can bind to each object property, without knowing the property values ahead of time.
Take this for example
var object1 =
{
Name: '1',
Identifier: '12345',
Password: 'password'
}
var object2 =
{
Name: '2',
Identifier: 'object_two'
}
var objects = [object1,object2];
My objects can have different and unique properties, and I'd like to bind this to a form.
I know I can use a for (var property in object) and iterate through each object -- But can I do the same thing with AngularJS binding?
I wanted to do something along the lines of:
<ul><li ng-repeat="attrib in obj">
{{attrib}}
</li</ul>
Edit: Thanks to the answer below I have gotten a little further. I can't seem to achieve two-way binding with this. This fiddle illustrates what I am trying to do:
http://jsfiddle.net/EpqMc/17/
I essentially want to bind using something like this:
<p ng-repeat="(key,value) in obj">
{{key}} : <input ng-model="obj[key]" />
</p>
This works, except that I can only enter one character at a time -- interesting.
Final Edit: I found an acceptable alternative in case anyone else has this problem. I wasn't able to bind directly to an object without some issues, but i WAS able to bind to an array like the docs state in the answer below.
The following fiddle accomplishes what I need to do, while being only slightly more verbose.
http://jsfiddle.net/8ENnx/9/
function ctrl($scope) {
$scope.objects =
[
[
{Name: 'Name:', Value: 'Joe'},
{Name: 'Identification', Value: '1'},
{Name: 'Password', Value: 'secret'}
],
[
{Name: 'Name:', Value: 'Jane'},
{Name: 'Identification', Value: '2'},
{Name: 'Weather', Value: 'Sunny'}
]
];
// $scope.setSelected = ?????;
}
<div ng-app>
<div ng-controller="ctrl">
Objects
<ul>
<br/>
Listing of properties:
<br/>
<li ng-repeat="obj in objects" class="swatch">
{{obj}}
<p ng-repeat="prop in obj">
{{prop.Name}}: <input ng-model="prop.Value" /></p>
</li>
</ul>
</div>
</div>
This allows me to define an arbitrary set of arguments, but still bind without issues using angular.
No problem:
<li ng-repeat='(key, value) in obj'>
{{key}} : {{value}}
</li>
It's in the docs as well: http://docs.angularjs.org/api/ng.directive:ngRepeat

Categories