Using angular to change class settings - angularjs

There is a lot of information on how to use ng-class and ng-style on elements. But I was wondering if there is a way to use angular to change the "settings" of a class.
So for example, say that you had a css class that looked as follows:
.testclass {
color: red;
background-color: blue;
}
I want to use angular to change the color:red to color:black, without attaching angular to the HTML DOM object, but via the class instead.
OK, this isn't a very useful example. What I was really planning to use it for was to hide part of ck-editor (class cle_top) and I want to set the whole class to hidden when someone clicks a button (and visible if the click it again).
======== To make it clearer, this is the bit of HTML I want to hide =======
<span id="cke_1_top" class="cke_top cke_reset_all" role="presentation" style="height: auto; -webkit-user-select: none;"><span id="cke_8" class="cke_voice_label">
Editor toolbars</span><span id="cke_1_toolbox" class="cke_toolbox" role="group" aria-labelledby="cke_8" onmousedown="return false;">
<span id="cke_11" class="cke_toolbar" aria-labelledby="cke_11_label" role="toolbar"><span id="cke_11_label" class="cke_voice_label">
But I need to do it without being able to add angular hooks in the HTML code (like adding ng-class to the span, which would have been a simple solution)
Attached is a JSfiddle that shows my problem, and as you can see, the toolbar button does nothing.
http://jsfiddle.net/vrghost/uqvo3ceh/
Which kind of works now, it adds the class invisible to the span, however, it does not hide the span that it is looking at.
Use the same process on a test text and it works...

Don't know of anything that will edit the class itself, but that probably isn't want you want to do. Other options are:
1) Create a second class, that comes after the first one in your CSS file that adds / changes the properties you want. Ex:
.testclass {
color: red;
background-color: blue;
}
.newclass {
color: green; // change property in first CSS class
display: none; // or hide
}
Then apply the second class conditionally:
<div class="text-class" ng-class="{newclass: hideScopeFlag}">blah</div>
2) Simply use ng-if, ng-hide, or ng-show if all you are doing is hiding something. Ex:
<div class="text-class" ng-hide="hideScopeFlag">blah</div>
or
<div class="text-class" ng-show="!hideScopeFlag">blah</div>

Why not simply toggle the class off/on for that element when the user clicks the button? (Edit: You said you want to "set the whole class to hidden" - I am assuming you mean to remove the class?)
To answer your question though, you can do this with JavaScript using document.styleSheets.
See this Stack Overflow question and the blog post it references. It mentions that there may be some browser compatibility issues. I have not investigated this.
EDIT: This implementation of 'ng-toggle' will allow you to hide or show an element with a single button.

The simplest solution without messing with the stylesheets is to add a new rule like
.visibleOff .testclass {
color: black;
}
and then you just need to toggle the "visibleOff" class on a parent element (the wrapper or the body element) of the editor.

To hide certain elements in the DOM you can also use a $scope variable that acts as a boolean. You can set it to false by default and on button click toggle it to true and back.
$scope.hidden = false;
$scope.toggleHide = function(){
$scope.hidden = !$scope.hidden;
}
In your dom you can then wrap your element with an ng-hide="hidden" attribute like so:
<div ng-hide="hidden">...</div>
<button ng-click="toggleHide()">togglehide</button>
A plunker example can be found here: http://plnkr.co/edit/?p=preview

If anyone wanted to know how to do this, potentially this could be useful for other things as well.
Created a function that uses document.querySelector to find the element, then just do a toggle to turn on or of, and that, as they say, is it folks.
$scope.toolBarVisible = function(){
console.log("Changing visibility");
var element = document.querySelector( '.cke_top' );
console.log("Just to do some debugging we check " + element);
var myEl = angular.element( element );
myEl.toggle();
element = document.querySelector( '.cke_bottom' );
myEl = angular.element( element );
myEl.toggle();
var myEl2 = angular.element( document.querySelector( '.test' ) );
myEl2.toggleClass("invisible")
}
And for those that are looking closely, yes, it hides the bottom as well, and all without changing ckeditor or the code.
Hope someone finds it helpful.

Related

How do I dynamically style uib-accordion-group

I have created a uib-accordion in my Angular website and can get most of the functionality I want, with dynamic content changing accordingly.
I am having trouble styling the uib-accordion-group dynamically.
<uib-accordion-group panel-class="panel-danger">
<uib-accordion-heading>
Accordion Heading 1
Is fine and colours the whole heading Red/Pink, I want to change this to panel-warning or panel-info based on other variables on the page.
<uib-accordion-group panel-class="{{getPanelColor()}}">
<uib-accordion-heading>
Accordion Heading 1
The function seems to be called correctly and is triggered correctly with ng-click elsewhere.
I appears that I cannot change the value panel-class uses dynamically. So in this instance getPanelColor() returns 'panel-danger', 'panel-info' or 'panel-warning' depending on other variables. If I print this return value out on the page in another div or whatever it changes correctly. If I refresh the page the correct colours are displayed for the changed panel-group.
Is there another way of setting the color - I don't know what the classes are for the accordion-group. I have tried changing the color of a div withing the panel, but this is a child element and does not change the color of the whole heading.
Any help much appreciated. (I'll come up with a JSFiddle if the question is not clear)
If you look at the HTML after the panel-class has changed and Angular has digested the change, you will see this line:
<div class="panel panel-danger" ... panel-class="panel-default">
That is, there is a mismatch between class and panel-class (the former has panel-danger, whereas the latter has panel-default). The uib-accordion-group directive simply does not handle the change in the wanted manner.
One workaround is to add ng-if to the whole group:
<uib-accordion-group ng-if="render" panel-class="{{getPanelColor()}}">
... and just before you want to change panel-class, remove the whole element temporarily, so that Angular re-renders it from scratch. Hopefully, the following code explains the principle:
$scope.render = true;
$scope.panelColor = 'panel-danger';
$scope.setPanelColor = function(val) {
$scope.panelColor = val;
$scope.render = false;
$timeout(function () {
$scope.render = true;
});
};
$scope.getPanelColor = function() {
return $scope.panelColor;
};
See the proposal in action: http://plnkr.co/edit/XfJiPnNi1z4F9cgIVxxw?p=preview. Press 'Clear panel color OK'.
The downside is that the removal of the element causes some flickering.
I have added another button 'Clear panel color FAIL' that shows what happens in your failing case. Here is what the HTML looks like after you press the button, notice the mismatch panel-danger vs. panel-default:
Use an interpolated expression in the class attribute, for example:
class="{{!ctrl.valid?'notValid':'valid'}}"

ng-show and ng-if lags to hide content

I have the following in to show and hide the clear button based upon if the searchQuery is empty or not. When a user starts typing in the input box, the button shows instantly.
However, when the user either clicks the clear button or deletes all input, there is a noticeable lag before the clear button is removed. I have tried ng-show as well, and have received the same results. Any ideas why this lag might exist?
HTML
<button ng-if="search.cardsQuery.length" class="button-icon" ng-click="clearSearchQuery()">
<i class="ion-android-close search-cards"></i>
</button>
CONTROLLER
$scope.clearSearchQuery = function() {
$scope.search.cardsQuery = '';
};
Check the css class on the element you're applying ng-if/ng-show to. Look for the transition effect. If the class has a transition, it may be the cause to the delay:
.button-icon {
transition: all .5s;
}
Its a common problem seen among the developers. Even trying with ng-if causes the same issue. I can suggest a simple solution for you.
Open your css file for the particular html file and add below line.
**.ng-hide { display: none !important }**
Hope, it will help.
$scope.$evalAsync();
Worked for me :)

backbone js add printing region dynamically

I have a requirement to print the View model data using Print Button.
Currently i have a div and assigning my view content to it. This div has been already added in backbone region. In my javascript function, i am just setting the viewmodel content to the printdiv and it working with out any issue.
But the content which i have added for printing is getting appended in the browser HTML also, I dont want to show that in my browser. I tried setting visible hidden and display none to my printingdiv. but then printing is not working since the content is not visible
CSHTML:
<div id="printdiv"/>
JS:
Myapp.printdiv.show(viewData.view);
window.print();
Init.JS
Myapp.addRegions({
printdiv: '#printdiv',
});
Please help me to resolve this issue
Thanks
The best way to handle this sort of problem is with a print-specific stylesheet. This article explains how to do that in detail, but the short version is that you define your non-print styles as normal, then use CSS code like the following to override print-specific styles:
#printdiv {
display: none
}
#media print {
#printdiv {
display: block;
}
}

center form content modifying form.html template

I'm still using 4.1 and I'm trying to center a form content on screen.
When I add a new form it stays on the "left" of the screen.
I've tried to change form.html (temmplates/shared) adding a div with a style like this:
margin-left : 10%; margin-right : 10%;
up next to the form tag and closing it at the bottom.
The form goes to the right but not centered at all.
Anyone has any clue to help with this ?
Here is a screenshot of a simple Form (it's not basec on models)
thanks
Alejandro
Ok - i've gone to a default of atk4.2 to demonstrate.
If you add a new page with defaults as follows
<?php
class page_test extends Page {
function init() {
parent::init();
$p=$this;
$f=$p->add('MVCForm')->setModel('Customer');
}
}
?>
I get the following and the fields extend across the whole width of the page.
This is because the default page template takes the whole width and is expected.
In order to adjust the form, you can use view functionality so create a view under the /lib/View directory called Centre.php and put the following code in it
<?php
class View_Centre extends View {
function init(){
parent::init();
}
function defaultTemplate() {
return array('view/centre');
}
}
?>
Then create a new template for the view in yoursite/templates/default/view called centre.html and insert the following html code
<div style='width:50%; margin: auto;'>
<?$Content?>
</div>
and then in the page, we add the view first and the form into the view rather than straight into the page.
<?php
class page_test extends Page {
function init() {
parent::init();
$p=$this;
$v=$p->add('View_Centre');
$f=$v->add('MVCForm')->setModel('Customer');
}
}
?>
and this results in the following web page
The base ATK4 form is itself a view which means you can style the form however you want so if you get for example use a different style of form such as the one described here you can do this by copying yoursite/atk4/atk4/templates/shared/form.html to yoursite/atk4/templates/shared.form.html and changing the second line from
<?form?>
<div id="<?$_name?>" class="atk-form <?$class?>" style="<?$style?>">
<?$hint?>
<form class="<?$form_internal_class?>" id="<?$form_name?>" name="<?$form_name?>" action="<?$form_action?>" method="POST" <?$enctype?>>
<fieldset class="<?$fieldset?>">
to
<?form?>
<div id="stylized>" class="myform <?$class?>" style="<?$style?>">
<?$hint?>
<form class="<?$form_internal_class?>" id="<?$form_name?>" name="<?$form_name?>" action="<?$form_action?>" method="POST" <?$enctype?>>
<fieldset class="<?$fieldset?>">
Create a new form.css file in yoursite/templates/default/css which contains the styling
Copy yoursite/atk4/templates/shared/shared.html to yoursite/templates/shared/shared.html and add an extra tag
<?$css_include?>
just above the existing
<?$js_include?>
and in Frontend.php, let every page find the new css file.
$this->addLocation('templates',array(
'css'=>array(
'default/css',
),
));
$this->template->appendHTML('css_include','<link type="text/css" href="'.$this->api->locateURL('css','form.css').'" rel="stylesheet">');
which results in a styled form like this
There are some examples of different form layouts here that you can use to adjust the form layout itself. Not sure from your question if you want to center the form in the page or centre the fields.
If you just want to centre the Form within the webpage, you want to use margin: auto for centering css rather than setting a percentage on each side as shown here
Also note, if you amend files from the atk4 directory, you should make a copy into yoursite/templates/shared and amend it there so you can upgrade by overwriting the atk4 directory later without losing anything.
If i use the default form template (in this case in a CRUD), i get the following
If i make your change to the atk4/templates/form.html by adding
<div style="width: 50%; margin: 0 auto;">
as the second line in form.html and adding the corresponding
</div>
one line from the bottom, it shifts everything slightly to the right as follows
What is unclear in your question is what you are trying to achieve - do you want to move the fields within the form or do you want to centre the whole form on the page ?
I think the reason for the shifting is because of setting the width to 50% but I dont know what layout you are trying to obtain - do you just want to right align the labels to the fields maybe ? Please post screenshots in the original question of what you are getting and try to describe what you want to achieve.

Fluid like box?

I'm making a responsive site and need to include a Facebook Like-Box for the client's Facebook fanpage. The developer page for the like-box has a widget for customization, but it doesn't allow you to set a width in percentages.
I've searched around and the closest I've got was this page from 2010, which refers to a fb:fan widget that allows you to link custom CSS. I tried to get this tutorial to work but it fails with this error:
<fb:fan> requires one of the "id" or "name" attributes.
So, to recap, I need a Facebook Like Box that I can either set up to be fluid, or which allows me to pass custom CSS to the iFrame it generates. Anyone able to point me in the right direction?
I found this Gist today and it works perfectly: https://gist.github.com/2571173
/* Make the Facebook Like box responsive (fluid width)
https://developers.facebook.com/docs/reference/plugins/like-box/ */
/* This element holds injected scripts inside iframes that in
some cases may stretch layouts. So, we're just hiding it. */
#fb-root {
display: none;
}
/* To fill the container and nothing else */
.fb_iframe_widget, .fb_iframe_widget span, .fb_iframe_widget span iframe[style] {
width: 100% !important;
}
You thought it couldn't be done? AHA! Have at you, Facebook and your wicked fixed-width ways: I wrote a JQuery script to undo all your evil!
$(document).ready(function(){
var fbWidth;
function attachFluidLikeBox(){
// the FBML markup: WIDTH is a placeholder where we'll insert our calculated width
var fbml = '<fb:like-box href="http://www.facebook.com/YOURFANPAGEORWHATEVS" width="WIDTH" show_faces="false" stream="true"></fb:like-box>';//$('#likeBoxTemplate').text().toString();
// the containing element in which the Likebox resides
var container = $('#likebox');
// we should only redraw if the width of the container has changed
if(fbWidth != container.width()){
container.empty(); // we remove any previously generated markup
fbWidth = container.width(); // store the width for later comparison
fbml = fbml.split('WIDTH').join(fbWidth.toString()); // insert correct width in pixels
container.html(fbml); // insert the FBML inside the container
try{
FB.XFBML.parse(); // parses all FBML in the DOM.
}catch(err){
// should Facebook's API crap out - wouldn't be the first time
}
}
}
var resizeTimeout;
// Resize event handler
function onResize(){
if(resizeTimeout){
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(attachFluidLikeBox, 200); // performance: we don't want to redraw/recalculate as the user is dragging the window
}
// Resize listener
$(window).resize(onResize);
// first time we trigger the event manually
onResize();
});
What is does is it adds a listener to the window's resize event. When it resizes, we check the width of the Likebox' containing element, generates new XFBML code with the correct width, replaces the containing element's children with said XFBML and then trigger the Facebook API to parse the XFBML again. I added some timeouts and checks to make sure it doesn't do anything stupid and only runs when it needs to.
Much has changed since the OP.
By simply choosing iFrame and setting your width to 100%, your FB Like Box should be responsive.
Basically FB adds this to the iFrame:
style="border:none; overflow:hidden; width:100%; height:300px;".
Been struggling with the exact same problem. A quick & simple solution is to use the iframe based Facebook Like box.
<iframe class="fb-like-box" src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&width=292&height=500&colorscheme=light&show_faces=true&border_color&stream=true&header=true" scrolling="no" frameborder="0" allowTransparency="true"></iframe>
Note the assigned 'fb-like-box' class and all the removed inline styles. The class for the iframe could look something like this:
.fb-like-box {
width: 100% !important;
height:500px;
border:none;
overflow:hidden;
}
Looks like it doesn't matter what the height and width are that are defined in the iframe's src tag. Just place the iframe into some fluid element like a cell in a CSS grid layout.
(includes ideas from: http://updateox.com/web-design/make-facebook-comment-and-like-box-fluid-width/)
I used the HTML5 version of Facebook Like Box and here is what worked for me:
.fb-like-box,
.fb_iframe_widget span,
.fb_iframe_widget iframe {
width:100% !important;
}
You cannot set the like-box to anything other than a pixel width. My suggestion is to place it in a DIV or SPAN that is fluid with overflow set to hidden. Sure, it's going to crop off part of the like-box, but by having the requirement of fluid, this is your best bet.
Here's a small work around that appends the HTML5 Facebook LikeBox Plugin into the DOM with a response height or width.
$(document).ready(function(){
var height = $(window).height();
var width = $(window).width();
var widget_height = parseInt((height)*0.9);
var widget_width = parseInt((height)*0.3);
var page_url = "http://www.facebook.com/Facebook";
$(".fb-plugin").append("<div class='fb-like-box'
data-href='"+page_url+"'
data-width='"+widget_width+"'
data-height='"+widget_height+"'
data-colorscheme='dark'
data-show-faces='true'
data-border-color='#222'
data-stream='true'
data-header='true'>
</div></div>");
});
The comment above from Ed and Matthias about using 100% for the iframe worked great for me. Here is my iframe code
ORIGINAL WITHOUT FIX:
<iframe src="//www.facebook.com/plugins/likebox.php?
href=https%3A%2F%2Fwww.facebook.com%2FXXXXXXXXXX&
width&height=290&colorscheme=dark&
show_faces=true&header=true&stream=false&
show_border=true&appId=XXXXXXXXXX"
scrolling="no" frameborder="0"
style="border:none; overflow:hidden; height:290px;"
allowTransparency="true"></iframe>
UPDATED WITH 100% FIX:
<iframe src="//www.facebook.com/plugins/likebox.php?
href=https%3A%2F%2Fwww.facebook.com%2FXXXXXXXXXX&
width&height=290&colorscheme=dark&
show_faces=true&header=true&stream=false&
show_border=true&appId=XXXXXXXXXX"
scrolling="no" frameborder="0"
style="border:none; overflow:hidden; height:290px;width:100%"
allowTransparency="true"></iframe>
The only change is adding "width:100%" to the style attribute of the iframe
note that the code above has "XXXXXXXXXX" in place of the unique references

Resources