How to read array element (json) in Angular - arrays

I have a var called $scope.informationData and the contents (as output by console.log) is like this:
{"completed":100,"pending":50,"defects":20,"overdue":10}
If I, in my HTML, use this though:
<div class="huge">{{ informationData.overdue }}</div>
Then it's empty. I don't think there's anything wrong with the binding though because if I do {{ informationData }} then it outputs the same JSON as above.
I think I'm just using the wrong syntax to read the data - what do I need to change informationData.overdue to in order to see the number 10 appear?

Deserialize the json
$scope.informationData = angular.fromJson($scope.informationData);

You should put your value in quotes not your keys.
Change your json like this::
{"completed":"100","pending":"50","defects":"20","overdue":"10"}
Or
{completed:"100",pending:"50",defects:"20",overdue:"10"}

Related

Laravel collect($array)->sortBy($value)->values() Is showing on screen

I have a little problème on sorting an array according to a value using Laravel, what i did is converting it into a collection with:
$array = collect($array)
Then i sorted it with:
$array = collect($array)->sortBy($sortingValue)
The result here is a collection, so the next step was to get my data as an array back again:
$array = collect($array)->sortBy($sortingValue)->values()
I then wrote this code between semicolons because it's nested in an html code, so got something like this:
{{$array = collect($array)->sortBy($sortingValue)->values()}}
This is working pretty good, i do have my array sorted according to the parameter i pasted to the function, the problem i have is that this is causing the results to show up on my page in a text format, at the place im executing this code!
Any idea on where this comes from ? im pretty sure it's because of the nested code, but i didn't figure out how to hide that text from my page, and only use the results for the rest of my project.
Thank you.
Using {{ }} to assign a variable is not the correct approach, as it is shorthand for echoing (printing) the code to your view. If you want to assign a variable in a .blade.php file, use the #php directive, or raw PHP tags:
#php $array = collect($array)->sortBy($sortingValue)->values(); #endphp
<?php $array = collect($array)->sortBy($sortingValue)->values(); ?>
Then, later in your code, you can do:
#foreach($array as $record){
{{ $record->id }}
...
#endforeach
(or any other, valid property)

How can I access an element of an associative Array in handlebars with dynamic id?

I am currently trying to access an associative array inside of an emberjs handlebars file. Accessing through hardcoded values is no problem, but I want to get the element based on a dynamic "index".
The code I have so far is
{{#each this.model.ambient as |sound|}}
<Ambientsound #buttonActive={{soundPlayers.[Bells]}} #sound={{sound}} #updateFunction={{action "updateSound"}}/>
{{/each}}
and the relevant section of the controller is:
soundPlayers: {"Bells":100,"Fireplace":30}
The code I have above works perfectly fine, but now I am trying to access the soundPlayers.[...] based on the value of sound.id, like so:
{{#each this.model.ambient as |sound|}}
<Ambientsound #buttonActive={{soundPlayers.[sound.id]}} #sound={{sound}} #updateFunction={{action "updateSound"}}/>
{{/each}}
The Value in sound.id is passed as a string and there's nothing I can do about that.
How can I cast sound.id into something that allows me to access the array, or phrase the handlebars query in a way so I can get the result from the array? I could also consider reshaping the array I have in my controller. Anything that helps is welcome!
First you should do {{soundPlayers.Bells}}.
Next you can use the get helper:
<Ambientsound #buttonActive={{get soundPlayers sound.id}} #sound={{sound}} #updateFunction={{action "updateSound"}}/>

AngularJS - trustAsHtml. Help Me Understand

I've been at this for too long.
Basically, I'm pulling information via json.
This works fine, but the information being pulled does not show up as HTML.
I've been trying to get trustAsHtml to work but I do not know what I'm doing wrong.
Here's my code:
Controller:
var pageControllers = angular.module('pageControllers', ['ngSanitize']);
pageControllers.controller('PackagesCtrl', function PackagesCtrl($scope, $sce, $http){
$http.get('scripts/all_packages.php').success(function(data){
$scope.packagesData = data;
});
});
I'm getting groups of data from the database fine. My data is rendering pure text instead of showing the actual html eg: <p class="myClass">My Returned Data</p>
My Html has an ng-repeat="item in packagesData"
and in that div I have:
ng-bind-html="item.more_info".
This returns the data I need, but how would I now make them render properly? Basically, from the returned fields, I need 2 results to show up as html, but everything I try does not work.
My json file returns multiple rows of data, e.g.:
[{"title":"My Title", "more_info":"<p>Information</p>"},{"title":"My Title 2", "more_info":"<p>Information 2</p>"}]
How do I target specific results such as "more_info" to show as html?
basically you right on your path. What you need to do is to check if its the right value with key. Key is you identifier for particular value.
The thing you need to do is to use an ng-if condition.
<h2 ng-if="key=='more_info'" ng-bind-html="value"></h2>

Reverse list in ng-repeat

So I have an array that I'm using ng-repeat to render out but I want to reverse this list. Previously I have used a filter which i got from this answer: angular ng-repeat in reverse
But now I get an error: "TypeError: Object # has no method 'slice'
at Scope." I'm not sure if this is because of a new version of AngularJS or I'm missing something.
This is my filter code:
.filter('reverse', function () {
return function(items) {
return items.slice().reverse();
};
This is the code from my view from inside the div:
data-ng-repeat='feed in feeds | reverse'
To make the array render in reverse and ordered by 'id', this should work:
data-ng-repeat="feed in feeds | orderBy:'id':true"
Let me know if that works for you.
For your reference: http://jsfiddle.net/byizzy/pgPVU/3/
This is a bit tricky, but for all the people interested in reversing an array without creating new predicate functions and/or modifying the array etc...
ng-repeat="feed in feeds | orderBy:'':true"
or
ng-repeat="feed in feeds | orderBy:'-'"
EXPLANATION
if you leave the second parameter a blank string, then Angular will sort by the default order of the array (index), adding true at the end will enable the reverse parameter of Angular' orderBy
Please use directly Java-script slice function with reverse like this:
data-ng-repeat="item in items.slice().reverse()"
What is the structure of a single feed? It seems you can use the built-in filter from angular to order it the way you want. For example, if the field "id" is what provides "order" in the array, you would do this:
data-ng-repeat='feed in feeds | orderBy:id'
If you want that reversed, you just do:
data-ng-repeat='feed in feeds | orderBy:id:reverse'
Does that make sense? Not sure you need your own filter. If that is the case, perhaps try debugging (i.e. write to the console or otherwise) to see what you are actually being passed. If it is not an array, that's your problem, otherwise try this instead:
return Array.prototype.slice.call(items).reverse();
Let me know if either of those work for you!
Hope this will solve your problem
data-ng-repeat='feed in feeds.reverse()'
a solution which doesn't sort the array, but only copies and reverses it:
ng-repeat="item in items | orderBy : '[]': true"
Another Alternative Way to Achieve the AngularJs Reverse is
<div ng-repeat="item in items | orderBy:'$index':true">
<code>{{item.id}} - {{item.name}}</code>
</div>

$sce.trustAsHtml vs. ng-bind-html

Why can't I do this:
<div>{{data | htmlfilterexample}}</div>
When, inside the filter, I am returning:
return $sce.trustAsHtml(input);
Using <div ng-bind-html="data | htmlfilterexample"></div> works regardless if the filter returns input or $sce.trustAsHtml(input).
I was under the impression that $sce makes HTML trustworth and ng-bind-html isn't needed for output returned by that method.
Thanks.
$sce.trustAsHtml() produces a string that is safe to use with ng-bind-html. Were you to not use that function on the string then ng-bind-html would yield the error: [$sce:unsafe] Attempting to use an unsafe value in a safe context. So $sce doesn't get rid of the need for ng-bind-html rather it makes the string it processes safe to use with it.
The specific issue you're running into lies in the difference between ng-bind and ng-bind-html
Using {{}} is the equivalent of ng-bind. So, looking at the ng-bind source code (ng-bind-* source code) we see that it uses this:
element.text(value == undefined ? '' : value);
while ng-bind-html, amongst other things, does the following:
var parsed = $parse(attr.ngBindHtml);
element.html($sce.getTrustedHtml(parsed(scope)) || '');
The key takeaway being that the ng-bind use of .text (http://api.jquery.com/text/) results in the text representation of the string being displayed (ignoring whether it's HTML trustworthy).
While the ng-bind-html use of .html (http://api.jquery.com/html/) results in the html interpreted version (if declared safe by getTrustedHtml())

Resources