if else statement in AngularJS templates - if-statement

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.
I want to make a condition like this:
if video.yt$aspectRatio equals widescreen then
element's attr height="270px"
else
element's attr height="360px"
I'm iterating the videos using ng-repeat. Have no idea what should I do for this condition:
Add a function in the scope?
Do it in template?

Angularjs (versions below 1.1.5) does not provide the if/else functionality . Following are a few options to consider for what you want to achieve:
(Jump to the update below (#5) if you are using version 1.1.5 or greater)
1. Ternary operator:
As suggested by #Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:
<span>{{isLarge ? 'video.large' : 'video.small'}}</span>
2. ng-switch directive:
can be used something like the following.
<div ng-switch on="video">
<div ng-switch-when="video.large">
<!-- code to render a large video block-->
</div>
<div ng-switch-default>
<!-- code to render the regular video block -->
</div>
</div>
3. ng-hide / ng-show directives
Alternatively, you might also use ng-show/ng-hide but using this will actually render both a large video and a small video element and then hide the one that meets the ng-hide condition and shows the one that meets ng-show condition. So on each page you'll actually be rendering two different elements.
4. Another option to consider is ng-class directive.
This can be used as follows.
<div ng-class="{large-video: video.large}">
<!-- video block goes here -->
</div>
The above basically will add a large-video css class to the div element if video.large is truthy.
UPDATE: Angular 1.1.5 introduced the ngIf directive
5. ng-if directive:
In the versions above 1.1.5 you can use the ng-if directive. This would remove the element if the expression provided returns false and re-inserts the element in the DOM if the expression returns true. Can be used as follows.
<div ng-if="video == video.large">
<!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
<!-- code to render the regular video block -->
</div>

In the latest version of Angular (as of 1.1.5), they have included a conditional directive called ngIf. It is different from ngShow and ngHide in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:
<div ng-if="video == video.large">
<!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
<!-- code to render the regular video block -->
</div>

Ternary is the most clear way of doing this.
<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>

Angular itself doesn't provide if/else functionality, but you can get it by including this module:
https://github.com/zachsnow/ng-elif
In its own words, it's just "a simple collection of control flow directives: ng-if, ng-else-if, and ng-else." It's easy and intuitive to use.
Example:
<div ng-if="someCondition">
...
</div>
<div ng-else-if="someOtherCondition">
...
</div>
<div ng-else>
...
</div>

You could use your video.yt$aspectRatio property directly by passing it through a filter, and binding the result to the height attribute in your template.
Your filter would look something like:
app.filter('videoHeight', function () {
return function (input) {
if (input === 'widescreen') {
return '270px';
} else {
return '360px';
}
};
});
And the template would be:
<video height={{video.yt$aspectRatio | videoHeight}}></video>

In this case you want to "calculate" a pixel value depending of an object property.
I would define a function in the controller that calculates the pixel values.
In the controller:
$scope.GetHeight = function(aspect) {
if(bla bla bla) return 270;
return 360;
}
Then in your template you just write:
element height="{{ GetHeight(aspect) }}px "

I agree that a ternary is extremely clean. Seems that it is very situational though as somethings I need to display div or p or table , so with a table I don't prefer a ternary for obvious reasons. Making a call to a function is typically ideal or in my case I did this:
<div ng-controller="TopNavCtrl">
<div ng-if="info.host ==='servername'">
<table class="table">
<tr ng-repeat="(group, status) in user.groups">
<th style="width: 250px">{{ group }}</th>
<td><input type="checkbox" ng-model="user.groups[group]" /></td>
</tr>
</table>
</div>
<div ng-if="info.host ==='otherservername'">
<table class="table">
<tr ng-repeat="(group, status) in user.groups">
<th style="width: 250px">{{ group }}</th>
<td><input type="checkbox" ng-model="user.groups[group]" /></td>
</tr>
</table>
</div>
</div>

<div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>
you can use the ng-if directive as above.

A possibility for Angular:
I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.
The html part in the template:
<div *ngFor="let p of poemsInGrid; let i = index" >
<a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
</div>
And the typescript part:
produceFassungsLink(titel: string, iri: string) {
if(titel !== undefined && iri !== undefined) {
return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
} else {
return 'Linkinformation has not arrived yet';
}
}
Thanks and best regards,
Jan

ng If else statement
ng-if="receiptData.cart == undefined ? close(): '' ;"

Related

How do I scrape nested data using selenium and Python

I basically want to scrape Litigation Paralegal under <h3 class="Sans-17px-black-85%-semibold"> and Olswang under <span class="pv-entity__secondary-title Sans-15px-black-55%">, but I can't see to get to it. Here's the HTML at code:
<div class="pv-entity__summary-info">
<h3 class="Sans-17px-black-85%-semibold">Litigation Paralegal</h3>
<h4>
<span class="visually-hidden">Company Name</span>
<span class="pv-entity__secondary-title Sans-15px-black-55%">Olswang</span>
</h4>
<div class="pv-entity__position-info detail-facet m0"><h4 class="pv-entity__date-range Sans-15px-black-55%">
<span class="visually-hidden">Dates Employed</span>
<span>Feb 2016 – Present</span>
</h4><h4 class="pv-entity__duration de Sans-15px-black-55% ml0">
<span class="visually-hidden">Employment Duration</span>
<span class="pv-entity__bullet-item">1 yr 2 mos</span>
</h4><h4 class="pv-entity__location detail-facet Sans-15px-black-55% inline-block">
<span class="visually-hidden">Location</span>
<span class="pv-entity__bullet-item">London, United Kingdom</span>
</h4></div>
</div>
And here is what I've been doing at the moment with selenium in my code:
if tree.xpath('//*[#class="pv-entity__summary-info"]'):
experience_title = tree.xpath('//*[#class="Sans-17px-black-85%-semibold"]/h3/text()')
print(experience_title)
experience_company = tree.xpath('//*[#class="pv-position-entity__secondary-title pv-entity__secondary-title Sans-15px-black-55%"]text()')
print(experience_company)
My output:
Experience title : []
[]
Your XPath expressions are incorrect:
//*[#class="Sans-17px-black-85%-semibold"]/h3/text() means text content of h3 which is child of element with class name attribute "Sans-17px-black-85%-semibold". Instead you need
//h3[#class="Sans-17px-black-85%-semibold"]/text()
which means text content of h3 element with class name attribute "Sans-17px-black-85%-semibold"
In //*[#class="pv-position-entity__secondary-title pv-entity__secondary-title Sans-15px-black-55%"]text() you forgot a slash before text() (you need /text(), not just text()). And also target span has no class name pv-position-entity__secondary-title. You need to use
//span[#class="pv-entity__secondary-title Sans-15px-black-55%"]/text()
You can get both of these easily with CSS selectors and I find them a lot easier to read and understand than XPath.
driver.find_element_by_css_selector("div.pv-entity__summary-info > h3").text
driver.find_element_by_css_selector("div.pv-entity__summary-info span.pv-entity__secondary-title").text
. indicates class name
> indicates child (one level below only)
indicates a descendant (any levels below)
Here are some references to get you started.
CSS Selectors Reference
CSS Selectors Tips
Advanced CSS Selectors

CFdump and Bootstrap tooltips fight each other

I attach Bootstrap tooltips via
$("[title]").tooltip({ html: true });
When I use a <cfdump>, title tags are attached all over the place. The start of the <cfdump> html looks like this
<table class="cfdump_struct">
<tr><th class="struct" colspan="2" onClick="cfdump_toggleTable(this);" style="cursor:pointer;" title="click to collapse">struct</th></tr>
<tr>
<td class="struct" onClick="cfdump_toggleRow(this);" style="cursor:pointer;" title="click to collapse">Cause</td>
<td>
Is there a way to keep, the two from stepping on eachother?
You shouldn't care because cfdump shouldn't be used in production, however you could just reduce the array returned by the jQuery selector. Not sure if this is the best way to do it, but it works:
$("[title]").filter(function(){
return ($(this).closest(".cfdump_struct").length == 0);
}).tooltip({ html: true });
It runs the filter function for each item in the array returned by the selector. If it is within the CFDUMP table (signified by the .cfdump_struct class) it will not return it. You will have to extend this to other cfdump types (queries, etc) but this should get you started.
Again, it really shouldn't matter since you shouldn't be using cfdump in production code anyway.
You can see this in action here: http://jsfiddle.net/seancoyne/rc7TL/

CSS3 class match letter range [a-z]+?

Is there any possibility to create CSS definition for any element with the class "icon-" and then a set of letters but not numbers.
According to this article something like:
[class^='/icon\-([a-zA-Z]+)/'] {}
should works. But for some reason it doesn't.
In particular I need to create style definition for all elements like "icon-user", "icon-ok" etc but not "icon-16" or "icon-32"
Is it possible at all?
CSS attribute selectors do not support regular expressions.
If you actually read that article closely:
Regex Matching Attribute Selectors
They don’t exist, but wouldn’t that be so cool? I’ve no idea how hard it would be to implement, or how to expensive to parse, but wouldn’t it just be the bomb?
Notice the first three words. They don't exist. That article is nothing more than a blog post lamenting the absence of regex support in CSS attribute selectors.
But if you're using jQuery, James Padolsey's :regex selector for jQuery may interest you. Your given CSS selector might look like this for example:
$(":regex(class, ^icon\-[a-zA-Z]+)")
I answered this one on facebook but thought I'd best share here too :)
I haven't tested this so don't shoot me if it doesn't work :) but my guess would be to excplicitly target elements that contain the word icon in the classname, but to instruct the browser not to inlcude those classes containing numbers.
Example code:
div[class|=icon]:not(.icon-16, .icon-32, icon-64, icon-96) {.....}
Reference:
attribute selectors... (http://www.w3.org/TR/CSS2/selector.html#attribute-selectors):
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D).
:not selector...
(http://kilianvalkhof.com/2008/css-xhtml/the-css3-not-selector/)
Hope this helps,
Waseem
I tested my previous solution and can confirm that it DOES NOT work (see comment from BoltClock). This however does:
OP: "In particular I need to create style definition for all elements like "icon-user", "icon-ok" etc but not "icon-16" or "icon-32""
The required CSS code would look something like this:
/* target every element were the class name begins with ( ^= ) "icon" but NOT those that begin with ( ^= ) "icon-16", or "icon-32" */
*[class^="icon"]:not([class^="icon-16"]):not([class^="icon-32"]) {.....}
or
/* target every element were the class name begins with ( ^= ) "icon" but NOT those that contain ( *= ) the number "16" or the number "18" */
*[class^="icon"]:not([class*="16"]):not([class*="32"]) { ...... }
Test code:
<!DOCTYPE html>
<html>
<head>
<style>
div{border:1px solid #999;margin-bottom:1em;height:100px;}
*[class|=icon]:not([class|=icon-16]):not([class|=icon-32]) {background:red;color:white;}
</style>
</head>
<body>
<div class="icon-something">
<h4>icon-something</h4>
<p><strong>IS</strong> targeted therfore background colour will be red</p>
</div>
<div class="icon-anotherthing">
<h4>icon-anotherthing</h4>
<p><strong>IS</strong> targeted therfore background colour will be red</p>
</div>
<div class="icon-16-install">
<h4>icon-16-install</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
<div class="icon-16-redirect">
<h4>icon-16-redirect</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
<div class="icon-16-login">
<h4>icon-16-login</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
<div class="icon-32-install">
<h4>icon-32-install</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
<div class="icon-32-redirect">
<h4>icon-32-redirect</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
<div class="icon-32-login">
<h4>icon-32-login</h4>
<p>Is <strong>NOT</strong> targeted therfore no background colour</p>
</div>
</body>
</html>

What is the proper way to add a custom dashboard "box" in the Magento backend without editing default templates?

I am working on creating what I hope one day will be a publicly available Magento extension (this part I mention because it's important to me that I do the "right thing" here). One of the things I would like to do is add a box in the default Magento dashboard, basically a new "box" exactly like "Top 5 Search Terms" except with my own content. I would like my new custom box to be the last box that is displayed (ideally).
The issue that I'm running into is that the template that is responsible for rendering the dashboard calls out specific blocks to be rendered, and these blocks are nested inside of html. In other words, where often there is an area where child blocks will be rendered into a nice reasonable HTML element, in this situation it appears that specific blocks are rendered. Here is the contents of /app/design/adminhtml/default/default/template/dashboard/index.phtml
<div class="dashboard-container">
<?php echo $this->getChildHtml('store_switcher') ?>
<table cellspacing="25" width="100%">
<tr>
<td><?php echo $this->getChildHtml('sales') ?>
<div class="entry-edit">
<div class="entry-edit-head"><h4><?php echo $this->__('Last 5 Orders') ?></h4></div>
<fieldset class="np"><?php echo $this->getChildHtml('lastOrders'); ?></fieldset>
</div>
<div class="entry-edit">
<div class="entry-edit-head"><h4><?php echo $this->__('Last 5 Search Terms') ?></h4></div>
<fieldset class="np"><?php echo $this->getChildHtml('lastSearches'); ?></fieldset>
</div>
<div class="entry-edit">
<div class="entry-edit-head"><h4><?php echo $this->__('Top 5 Search Terms') ?></h4></div>
<fieldset class="np"><?php echo $this->getChildHtml('topSearches'); ?></fieldset>
</div>
</td>
<td>
<div class="entry-edit" style="border:1px solid #ccc;">
<?php echo $this->getChildHtml('diagrams') ?>
<?php if (is_array($this->getChild('diagrams')->getTabsIds())) : ?>
<div id="diagram_tab_content"></div>
<?php endif; ?>
<div style="margin:20px;">
<?php echo $this->getChildHtml('totals') ?>
</div>
<div style="margin:20px;">
<?php echo $this->getChildHtml('grids') ?>
<div id="grid_tab_content"></div>
</div>
</div>
</td>
</tr>
</table>
</div>
If I was doing this in my own store, I believe I could achieve this relatively easily by editing the base Magento dashboard template index.phtml above, add what I need to have my block render, something like:
<div class="entry-edit">
<div class="entry-edit-head">
<h4><?php echo $this->__('Top 5 Search Terms') ?></h4></div>
<fieldset class="np"><?php echo $this->getChildHtml('myDashboardBox'); ?></fieldset>
</div>
</div>
But, this isn't my own store, so this doesn't really seem like an option.
Now, after some thought my options seem to be as follows (note that most of these seem "bad" and not something I'd be super proud to have seen in the public):
0) Something obvious that I'm not seeing that you will tell me is the perfect/right solution
1) I might (maybe?) be able to add my custom block inside of one of these other blocks in this area ("topSearches", "sales", etc) and have my block rendered. This does not seem very "clean"
2) I might be able to have the block rendered somewhere else on the dashboard page, and then move it with javascript to the correct place. This would be fairly easy I'm guessing, but feels very "hacky" for obvious reasons.
Does anybody have any feedback on the way to do this, or IF there is a way? Keep in mind that again I would like to release this module publicly so my goal is to do a good job and do as little "hacking" as possible.
Thank you very much for reading!
There is no really clean option, as you said, the template is coded in a non-extendable way, so there will always be some degree of hackiness. This is my personal preferred way of doing it by using event observers. This way it at least doesn't conflict with other modules.
First, add an observer for the core_block_abstract_prepare_layout_after and core_block_abstract_to_html_after event.
<adminhtml>
<events>
<core_block_abstract_prepare_layout_after>
<observers>
<your_module>
<class>your_module/observer</class>
<method>coreBlockAbstractPrepareLayoutAfter</method>
</your_module>
</observers>
</core_block_abstract_prepare_layout_after>
<core_block_abstract_to_html_after>
<observers>
<your_module>
<class>your_module/observer</class>
<method>coreBlockAbstractToHtmlAfter</method>
</your_module>
</observers>
</core_block_abstract_to_html_after>
</events>
</adminhtml>
These two events are dispatched for every block that is instantiated and rendered in Mage_Core_Block_Abstract. In my experience it's not such an issue using them in the adminhtml interface, but on the frontend observers for these events add too much overhead.
Back to the task at hand, you need to create the observer class.
class Your_Module_Model_Observer
{
public function coreBlockAbstractPrepareLayoutAfter(Varien_Event_Observer $observer)
{
if (Mage::app()->getFrontController()->getAction()->getFullActionName() === 'adminhtml_dashboard_index')
{
$block = $observer->getBlock();
if ($block->getNameInLayout() === 'dashboard')
{
$block->getChild('topSearches')->setUseAsDashboardHook(true);
}
}
}
public function coreBlockAbstractToHtmlAfter(Varien_Event_Observer $observer)
{
if (Mage::app()->getFrontController()->getAction()->getFullActionName() === 'adminhtml_dashboard_index')
{
if ($observer->getBlock()->getUseAsDashboardHook())
{
$html = $observer->getTransport()->getHtml();
$myBlock = $observer->getBlock()->getLayout()
->createBlock('you_module/block')
->setTheValuesAndTemplateYouNeed('HA!');
$html .= $myBlock->toHtml();
$observer->getTransport()->setHtml($html);
}
}
}
}
Your template will need to accomodate for the fact that you are inserting a sibling <div> from inside the sibling, but otherwise you should be fine.
</fieldset></div>
<div class="entry-edit">
<div class="entry-edit-head"><h4>Your Module</h4></div>
<fieldset class="np">Your Content
Leave it at that, because the parent template will be closing the <fieldset> and the <div> for you (ugly as heck, I know).

Find ColdFusion Generated ID

Is there a way to find the elements generated by ColdFusion's <CFLayout> and <CFLayoutArea> tags?
These tags:
<cflayout type="tab" name="MyAccount">
<cflayoutarea name="OrderStatus" title="P" source="/o.cfm" />
Generate this code:
<td id="ext-gen31" style="width: 174px;">
<a id="ext-gen28" class="x-tabs-right" href="#">
<span class="x-tabs-left">
<em id="ext-gen29" class="x-tabs-inner" style="width: 154px;">
<span id="ext-gen30" class="x-tabs-text" title="P" unselectable="on" style="width: 154px;">
I want to update the title information in the id of ext-gen30 but don't know what that name is going to be or how to find it.
It doesn't directly answer your question, but if your goal is to get a reference to the DOM objects in order to set their properties (and it sounds like that's the case), then the documentation suggests that you should be able to use the function ColdFusion.Layout.getTabLayout() to get a reference to the Ext layout object, and then manipulate that however you'd like.