Angular conditional container element - html

I have a large chunk of HTML in an ng-repeat that for certain elements has a container element and for others it does not. I'm currently achieving this with two ng-ifs:
<strike ng-if="elem.flag">
… <!-- several lines of directives handling other branching cases -->
</strike>
<div ng-if="!elem.flag">
… <!-- those same several lines copied-and-pasted -->
</div>
While this works, it means I have to remember copy-and-paste any edits, which is not only inelegant but also prone to bugs. Ideally, I could DRY this up with something like the following (inspired by ng-class syntax):
<ng-element="{'strike':flag, 'div':(!flag)}">
… <!-- lots of code just once! -->
</ng-element>
Is there any way to achieve a similarly non-repetitive solution for this case?

You can make such directive yourself.
You can use ng-include to include the same content into both elements.

Assuming the effect you desire is to have the text within your tag be striked through based on the condition of the elem.flag:
You could simply use the ng-class as follows
angular.module('ngClassExample', [])
.controller('elemController', Controller1);
function Controller1() {
vm = this;
vm.flag = true;
vm.clickItem = clickItem
function clickItem() {
// Toggle the flag
vm.flag = !vm.flag;
};
}
.strikethrough{
text-decoration: line-through
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='ngClassExample' ng-controller="elemController as elem">
<div ng-class="{strikethrough: elem.flag}" ng-click="elem.clickItem()">
element content should be sticked through: {{elem.flag}}
</div>
</div>

You can do it with a directive
module.directive('myFlag', function() {
var tmpl1 = '<strike>...</strike>';
var tmpl2 = '<div>...</div>';
return {
scope: {
myFlag: '='
},
link: function(scope, element) {
element.html(''); // empty element
if (scope.myFlag) {
element.append(tmpl1);
} else {
element.append(tmpl2);
}
}
};
});
And you just use it like:
<div ng-repeat="item in list" my-flag="item.flag"></div>

You could create a directive which will transclude the content based on condition. For tranclusion you could use ng-transclude drirective, in directive template. Also you need to set transclude: true.
HTML
<my-directive ng-attr-element="{{elem.flag ? 'strike': 'div'}}">
<div> Common content</div>
</my-directive>
Directive
app.directive('myDirective', function($parse, $interpolate) {
return {
transclude: true,
replace: false, //will replace the directive element with directive template
template: function(element, attrs) {
//this seems hacky statement
var result = $interpolate(attrs.element)(element.parent().scope);
var html = '<'+ result + ' ng-transclude></'+result+'>';
return html;
}
}
})
Demo Plunkr

You can also use ng-transclude :
Create your directive :
<container-directive strike="flag">
<!-- your html here-->
</container-directive>
Then in your directive do something like :
<strike ng-if="strike">
<ng-transclude></ng-transclude>
</strike>
<div ng-if="!strike">
<ng-transclude></ng-transclude>
</div>

Related

How to make links clickable in a chat

I have a chat on my website that reads from a JSON file and grabs each message and then displays it using Vue.js. However, my problem is that when a user posts a link, it is not contained in an anchor tag <a href=""/>. Therefore it is not clickable.
I saw this post, and I think something like this would work, however, I am not allowed to add any more dependencies to the site. Would there be a way for me to do something similar to this without adding more dependencies?
Code for displaying the message.
<p v-for="msg in messages">
<em class="plebe">
<b> [ {{msg.platform.toUpperCase()}} ]
<span style="color: red" v-if="msg.isadmin">{{msg.user.toUpperCase()}}</span>
<span style="color: #afd6f8" v-else="">{{msg.user.toUpperCase()}}</span>
</b>
</em>:
{{msg.message}}
</p>
In a situation like this, its preferred to write a custom functional component.
The reason for this is the fact that we are required to emit a complex html structure, but we have to make sure to properly protect against xss attacks (so v-html + http regex is out of the picture)
We are also going to use render functions, because render functions have the advantage to allow for javascript that generates the html, having more freedom.
<!-- chatLine.vue -->
<script>
export default {
functional: true,
render: function (createElement, context) {
// ...
},
props: {
line: {
type: String,
required: true,
},
},
};
</script>
<style>
</style>
We now need to think about how to parse the actual chat message, for this purpose, I'm going to use a regex that splits on any length of whitespace (requiring our chat urls to be surrounded with spaces, or that they are at the start or end of line).
I'm now going to make the code in the following way:
Make a list for child componenets
Use a regex to find url's inside the target string
For every url found, do:
If the match isn't at the start, place the text leading from the previous match/start inside the children
place the url inside the list of children as an <a> tag, with the proper href attribute
At the end, if we still have characters left, at them to the list of children too
return our list wrapped inside a P element
Vue.component('chat-line', {
functional: true,
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
// https://vuejs.org/v2/guide/render-function.html#createElement-Arguments
render: function (createElement, context) {
const children = [];
let lastMatchEnd = 0;
// Todo, maybe use a better url regex, this one is made up from my head
const urlRegex = /https?:\/\/([a-zA-Z0-9.-]+(?:\/[a-zA-Z0-9.%:_()+=-]*)*(?:\?[a-zA-Z0-9.%:_+&/()=-]*)?(?:#[a-zA-Z0-9.%:()_+=-]*)?)/g;
const line = context.props.line;
let match;
while(match = urlRegex.exec(line)) {
if(match.index - lastMatchEnd > 0) {
children.push(line.substring(lastMatchEnd, match.index));
}
children.push(createElement('a', {
attrs:{
href: match[0],
}
}, match[1])); // Using capture group 1 instead of 0 to demonstrate that we can alter the text
lastMatchEnd = urlRegex.lastIndex;
}
if(lastMatchEnd < line.length) {
// line.length - lastMatchEnd
children.push(line.substring(lastMatchEnd, line.length));
}
return createElement('p', {class: 'chat-line'}, children)
},
// Props are optional
props: {
line: {
required: true,
type: String,
},
},
});
var app = new Vue({
el: '#app',
data: {
message: 'Hello <script>, visit me at http://stackoverflow.com! Also see http://example.com/?celebrate=true'
},
});
.chat-line {
/* Support enters in our demo, propably not needed in production */
white-space: pre;
}
<script src="https://unpkg.com/vue#2.0.1/dist/vue.js"></script>
<div id="app">
<p>Message:</p>
<textarea v-model="message" style="display: block; min-width: 100%;"></textarea>
<p>Output:</p>
<chat-line :line="message"></chat-line>
</div>
You can watch or write computed method for the variable having url and manupulate it to html content and then use v-html to show html content on the page
v-html

Replace element with razor textarea

I want to take a tag and replace with a #Html.textarea() razor html helper but it doesn't look as if JQuery can replace DOM elements with html helpers. How do I go about this?
using(#Html.BeginForm())
{
<a id="clickme">Edit</a>
<div>#Model.username</div>
}
How can I replace this div with #Html.Textarea ? JQuery could do it with div and input tags.
jQuery cannot replace a tag with #Html.TextArea() !
The TextArea helper method is a C# method, which gets executed when razor tries to render the view. This happens in your web server. jQuery is a client side library and anything you do with jQuery happens at client side, in your browser.
But all these helper methods ultimately generate some HTML for DOM elements. That means, you can use jQuery to manipulate visibility of that.
If you are trying to do something like an inline edit, you can use a script like this , to start with
First, render the text area along with your label div, but have it hidden initially. Also wrap the label,edit link and the hidden input inside a container div which we can use later to help with our jQuery selectors.
#using (#Html.BeginForm())
{
<div class="edit-item">
Edit
<div class="edit-label">#Model.FirstName</div>
#Html.TextAreaFor(a => a.FirstName,
new { style = "display:none;", #class = "edit-text" })
</div>
<div class="edit-item">
Edit
<div class="edit-label">#Model.UserName</div>
#Html.TextAreaFor(a => a.UserName,
new { style = "display:none;", #class = "edit-text" })
</div>
}
Now when the user clicks edit, you have to toggle the visibility of the label and hidden input and update the value of label after user done editing the value in the input element.
$(function () {
$("a[data-mode]").click(function (e) {
e.preventDefault();
var _this = $(this);
var c = _this.closest(".edit-item");
c.find(".edit-text").toggle();
c.find(".edit-label").toggle();
if (_this.attr("data-mode") === 'label') {
_this.attr("data-mode", 'edit');
_this.text("done");
} else if (_this.data("mode") === 'edit') {
c.find(".edit-label").text(c.find(".edit-text").val());
_this.text("edit");
_this.attr("data-mode", 'label');
}
});
});
This is a head start. You can optimize this code as needed.
Here is a working jsfiddle for your reference

One page html static mutlilanguage

I have a school assignment to create a one page html static.
I want to have some buttons to change the language but I don't want any addition like "index.html/en/" or "index.html?lang=en". I prefer to have it with CSS only but I don't know whether it is possible or not.
In short I just want a simply bilingual "index.html" and have buttons to change the content text.
I am new in html scripting so I'm looking for some sample code or some detailed tutorial will be help.
I suggest using JS/jQuery for that:
Have language mapping for each element that will be translated:
// Translations object:
var translations = {
'en': {
'home': 'Home',
'back': 'Back'
/* ... */
},
'lt': {
'home': 'Pradžia',
'back': 'Atgal'
/* ... */
}
};
// wait for all DOM elements to load
$(document).ready(function() {
// when button is clicked
$('.lang-btn').click(function() {
// take translations subset
var lang = translations[$(this).data('lang')];
// for each element that has "data-key" attribute
$('[data-key]').each(function() {
// change it's content to other language
$(this).text(lang[$(this).data('key')]);
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-page">
Language:
<button class="lang-btn" data-lang="en">En</button>
<button class="lang-btn" data-lang="lt">Lt</button>
<hr/>
Home
<button data-key="back">Back</button>
</div>
This code is not checking if there is such translation or not. You can improve this algo with fallback to English.
For SEO reasons I'd prefer to use /en/. Use a .htaccess file with mod_rewrite.
See here Create beautiful url’s with mod_rewrite
If it is just one page, so I assume the contain is not much. Try something simpler like:
function en() {
document.getElementById("content").innerHTML = "Example";
}
function de() {
document.getElementById("content").innerHTML = "Beispiel";
}
<div id="content">sample</div>
<button onclick="en()">English</button>
<button onclick="de()">German</button>

Character escaping in Polymer

I'm creating a component with Polymer which has a background image added with inline styles. The problem is that using double brackets inside parenthesis and quotes makes the {{imageurl}} act like a string. Any tips?
<div class="image-container" style="background-image: url( '{{imageurl}}' )">
Update: I've tried the method posted here with no luck.
What you will have to do is have a computed property that returns the style:
<div style$="{{divStyle}}">hi</div>
Note the use of $= here as were are data-binding to an attribute. See here for more info.
And your JavaScript:
Polymer({
is: "test-element",
properties: {
backgroundColor: {
type: String,
value: '#FF0000'
},
divStyle: {
computed: 'getDivStyle(backgroundColor)'
}
},
getDivStyle: function(backgroundColor) {
return 'background-color: ' + backgroundColor + ';';
}
});
See this plunker to see it in action.
String interpolation is not yet supported in Polymer 1.0. Use computed bindings instead.
<!-- Notice the `$` sign. Use attribute binding (`$=`) when binding native elements attribute -->
<div style$="{{_computeBackgroundImage(imageurl)}}"></div>
Polymer({
...
_computeBackgroundImage: function(url) {
return 'background-image: url('+url+');';
}
});

How to set value for dir-Attribute via AngularJS

I want to set the direction of the body-element depending on some logic inside the controller.
So if a language file has a certain value, i want to change from "ltr" to "rtl".
I know there is a way of setting HTML attributes via ng-attr-, but it's not working for dir.
I made a JSFiddle to show my problem. The question is:
How can I set the dir-attribute via the controller?
<div ng-controller="MyCtrl">
<div ng-attr-dir="{{direct}}">
<p>Test</p>
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.direct = "rtl";
}
Just use dir, instead of ng-attr-dir.
<div dir="{{direct}}">
Fiddle
It can be accomplished with a trivial directive:
myApp.directive("myDir", function() {
return {
link: function(scope, elem, attrs) {
attrs.$observe("myDir", function(newval) {
if( newval ) {
elem.attr("dir", newval);
}
else {
elem.removeAttr("dir");
}
});
}
};
});
Use it as:
<div my-dir="{{direct}}">
A forked fiddle: http://jsfiddle.net/34ch4qef/1/
Use inline style="direction:{{direct}}" instead .
http://jsfiddle.net/HB7LU/7373/
You have to use an Angular version the actually supports ngAttr ;) 1.0 doesn't.