Add attributes and innerHTML of AngularJS on the fly - javascript

Okay, I'm very new to angular and I read already about it from different sources to understand it well enough,
apparently I'm still struggling to make it work in some way,
I already had the simple htmlpage:
<html>
<body ng-app>
<div id="content"></div>
</body>
</html>
then, after I request the data to the server, I create something like this:
function updateView($scope){
$scope.test="Success";
}
window.onload=function(){
var content = document.getElementById("content");
var add = document.createElement("div");
add.innerHTML = "{{test}}";
content.appendChild(add);
content.setAttribute("ng-controller", "updateView");
};
and what I got as a result was an html page with a text : {{test}}
so I assume that it's not working,
I know that this might have something to do with creating the content and ng-controller on the fly, and this can be accomplished in more basic way as many tutorial does, but I need the method I specified (add attribute and content(test) on the fly) because I will display something I request from the server which can have varied amount of data, say if it has 3 data in an array form, the "var add=document.createElement("div")" will be called 3 times and I will need to attach the attribute ng-controller to each of them
Is there a work around that I haven't known yet?

In order to accomplish what you are trying to do in Angular you will need to use the $compile service, which you can read more about here. This allows you to append html to the dom and link it to your scope variables.
For your specific example you could get the $compile service in the window.onload method like this:
window.onload=function(){
angular.element("body").injector().invoke(function ($compile) {
var content = document.getElementById("content");
var add = document.createElement("div");
add.innerHTML = "{{test}}";
content.appendChild(add);
content.setAttribute("ng-controller", "updateView");
$compile(template.contents())(scope);
});
};

Related

Add complexe Javascript array elements to HTML [duplicate]

I have a template:
function useIt() {
var content = document.querySelector('template').content;
// Update something in the template DOM.
var span = content.querySelector('span');
span.textContent = parseInt(span.textContent) + 1;
document.querySelector('#container').appendChild(
document.importNode(content, true));
}
<button onclick="useIt()">Use me</button>
<div id="container"></div>
<template>
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</template>
You can try the code here.
This code basically copies the template(html5 templates does not render on your screen) into another div. This allows you to reuse the DOM.
Problem: The line "span.textContent = parseInt(span.textContent) + 1;" changes the template code directly. I need to manipulate the content DOM and clone it into the container, without changing the template. This is very important since if I want to reuse the code, I need it to stay the same.
I have tried multiple ways to use jQuery to mimic the above javascript code, but I can't manage to figure it out. It would be better if there is a jQuery way.
If you NEED to use the new <template> tag, then you are mildly stuck . . . your cleanest alternative is to use importNode to bring in the content and then modify it after it's been appended.
Assuming that the templated code is realtively small, this should happen fast enough that you would never notice the difference in approach, though, in this specific example, the alert(), would delay the change of the content, so you would see "0", until you clicked "Okay", and then it would update to "1".
The code change for that would be:
function useIt() {
var content = document.querySelector('template').content;
var targetContainer = document.querySelector('#container');
targetContainer.appendChild(document.importNode(content, true));
var $span = $(targetContainer).find("div:last-of-type").find("span");
$span.text(parseInt($span.text() + 1));
}
If you are not married to the idea of <templates>, you could use jQuery's clone() method to do what you want to do, very easily . . . but, clone does not "see" the content of a <template>, due to the special nature of that particular element, so you would have to store the templated code some other way (JS variable, hidden div, etc.).
HOWEVER, this method will not work if you need to clone a script, the way that a <template> will. It will not trigger any script code in the "template container" element when the cloned version is created or appended. Additionally, if you store it in a hidden <div>, any script code in the "template container" element will trigger immediately on page load.
A simple version of the code for the clone() approach would look something like this:
function useIt() {
var $content = $("#template").clone();
var $span = $content.find("span");
$span.text(parseInt($span.text()) + 1);
$content.children().each(function() {
$("#container").append($(this));
});
}
Assuming that your template was:
<div id="template" style="display: none;">
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</div>
You could also move the <script>alert('Thanks!')</script> out of the template and into the script section (after you completed the "append loop"), to achive the desired alert functionality, if you wanted to.
It's an old question, but, did you try cloneNode(true)? It works on templates, as this:
var span = content.querySelector('span').cloneNode(true)
regards.

How do I define a variable in my index.html file? (window.parentPage = true;)

https://stackoverflow.com/a/43635720
On this answer, it says to define a variable (window.parentPage = true;) in the index.html page. How can I go about doing this?
You would need to define the variable using JavaScript. You can embed some JavaScript in the HTML file by encasing it in a script tag like so:
<script type="text/javascript">
window.parentPage = true;
</script>
First you need to clearly realize your reason... what you want to achieve.
After that defining that to yourself:
First option:
You can store/save some data as stated on the link you added to your question inside a tag, like that:
<script>
var myLittleBox = "box content";
</script>
And access it later like:
<script>
myLittleBox = myLittleBox + " extra content";
console.log(myLittleBox);
//this will print "box content extra content"
</script>
You need to use the tag to access the javascript environment.
Second option:
You can save/store data with pure HTML using an with type "hidden" to not show it on screen as an input box, and changing it's value, like that:
<input type="hidden" value="box content">
But this way you'll not be able to access the data directly without aid of javascript code, unless you send this input somewhere reachable as GET or POST within a and recover it getting the respective GET or POST.
Javascript variables:
https://www.w3schools.com/js/js_variables.asp
Ex: https://www.w3schools.com/js/tryit.asp?filename=tryjs_variables
HTML input:
https://www.w3schools.com/tags/tag_input.asp
HTML form handling:
https://www.w3schools.com/php/php_forms.asp
You're probably trying to understand the first option, but you question do not make that clear. Anyway, good studies.
Whatever you do you will have to use JavaScript in order to access the variable. An orthodox way of doing it that is not mentioned yet is using an data-attribute inside the html and than you access it by JavaScript:
const attributeName = 'data-parentPage';
const setup = () => {
let parentPageBool = document.querySelector(`html[${attributeName}]`).getAttribute(attributeName);
console.log(parentPageBool)
};
window.addEventListener('load', setup);
<html data-parentPage="true">
</html>

Add contents to a new empty iframe

I have a new iframe. It takes src and includes a completely empty page. Now I want to fill it with data trough javascript.
In normal cases I can do this:
var content = "Some content";
$("iframe").contents().find("body").html(content);
But this iframe is empty and has no body or html. Is it possible to include content to it anyway?
Something like this should be inserted:
<html>
<head></head>
<body>Hello</body>
</html>
Update
I can do this:
$('iframe').contents().find('html').html('<html><body>test</body></html>');
I don't know if it will render double html tags or not. In the developer tool I can't see that it add an extra.
You can get hold of the IFrame window by a normal query selector.
var myFrameDoc = document.getElementById('iframe_id').contentDocument;
If it has nothing, write it.
myFrameDoc.write('<html>');
myFrameDoc.write('<head>');
myFrameDoc.write('</head>');
myFrameDoc.write('<body>');
myFrameDoc.write('<div>Hello iFrame</div>');
myFrameDoc.write('</body>');
myFrameDoc.write('</html>');
There are more ways you can do this. I will leave it for you to realize.
In jQuery it seems to be no solution. Instead I needed to do it like this:
var content = '<html><head></head><body>Hello</body></html>';
var iframe = document.getElementById( '#iframe_id' );
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(content);

get the text of div using angularjs

i want to get the text of div using angularjs . I have this code
<div ng-click="update()" id="myform.value">Here </div>
where as my controller is something like this
var myapp= angular.module("myapp",[]);
myapp.controller("HelloController",function($scope,$http){
$scope.myform ={};
function update()
{
// If i have a textbox i can get its value from below alert
alert($scope.myform.value);
}
});
Can anyone also recommand me any good link for angularjs . I dont find angularjs reference as a learning source .
You should send the click event in the function, your html code should be :
<div ng-click="update($event)" id="myform.value">Here </div>
And your update function should have the event parameter which you'll get the div element from and then get the text from the element like this :
function update(event)
{
alert(event.target.innerHTML);
}
i just thought i put together a proper answer for everybody looking into this question later.
Whenever you do have the desire to change dom elements in angular you need to make a step back and think once more what exactly you want to achieve. Chances are you are doing something wring (unless you are in a link function there you should handle exactly that).
So where is the value comming, it should not come from the dom itself, it should be within your controller and brought into the dom with a ng-bind or {{ }} expression like:
<div>{{ likeText }}</div>
In the controller now you can change the text as needed by doing:
$scope.likeText = 'Like';
$scope.update = function() {
$scope.likeText = 'dislike';
}
For angular tutorials there is a good resource here -> http://angular.codeschool.com/
Redefine your function as
$scope.update = function() {
alert($scope.myform.value);
}
A better way to do it would be to use ng-model
https://docs.angularjs.org/api/ng/directive/ngModel
Check the example, these docs can be a bit wordy

How to get Text of Nested Span HTML element?

I want to get text from Nested SPAN element in Following HTML code:
<span id='result_box'>
<span class="hps">text_content</span>
</span>
I want to get "text_content" value using JavaScript.
I have tried this but have a problem:
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);
EDIT: Actually i want to do this from Online Page
your code works fine. i guess your problem is you are executing these code when DOM not loaded completely.if you are testing something, you can try this.
window.onload = function () {
//put your code here,it will alert when page loaded completely.
};
or put the script after your span element. like this.
<span id='result_box'>
<span class="hps">text_content</span>
</span>
<script type='text/javascript'>
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);// it will alert
</script>
you get the element by classname.. document.getElementsByClassName() and then grabbing the first item off the resulting node list
window.onload = function () {
document.getElementsByClassName("hps")[0].innerHTML
};
jsfiddle
var resBox=document.getElementById('result_box');
var strTrans=document.getElementsByTagName('span')[0].innerText;
alert(strTrans);​
or better
strTrans = document.querySelector(".hps").innerText ;
got you, i guess you embed a link in your html page,then you wanna manipulate DOM in the page you embed,right? if so, you can check browser same origin policy.
if you wanna implement online translation via google, you can google 'google translate api', google provides a api to others for implementing online translation in their own applications.
it seems like bing also provides a api.i'm not sure.

Categories