How to run javascript using ng-bind-html - javascript

I am using ng-bind-html which is running html code fine but when I tried to run JavaScript code using script tag it did not work. see example over here (Fiddle).
app.js file
app.constant('text',"<script>alert('this is alert')</script>");
app.constant('color', 'blue' );
controller.js
var module = angular.module('cntrl');
module.controller('DCtrl', function(
$scope,
$timeout,text,color) {
$scope.bannertext=text;
$scope.bannercolor=color;
});
frontend.html
<div ng-bind-html="bannerText"> </div>
this is giving me normal text like <script>alert('this is alert')</script> so how i can run javascript uisng above code

Imcomplete answer, but see changed JSFiddle at: https://jsfiddle.net/km31gwvx/1/
Replace < with < entity
Specify Angular as library in Frameworks and Extensions

Related

How can I importing external JS file in Ionic 3

I am finding problem in adding the external js file to Ionic 3. Here is what I did, I have created a hamburg.js file in src/js/hamburg.js, and called the script file in index.html at app/index.html. And I have added the html code in testpage.hmtl and css in testpage.scss. Also declared in app.component.ts. Here is my code
app.component.ts
declare var wrapperMenu;
hamburg.js
var wrapperMenu = document.querySelector('.wrapper-menu');
wrapperMenu.addEventListener('click', function(){
wrapperMenu.classList.toggle('open');
})
index.html
<script src="assets/js/hamburg.js"></script>
testpage.html
<div class="wrapper-menu">
<div class="line-menu half start"></div>
<div class="line-menu"></div>
<div class="line-menu half end"></div>
Can somebody guide me please?
There is no need to external js file, this plugin play mostly with CSS.
this snippet
var wrapperMenu = document.querySelector('.wrapper-menu');
wrapperMenu.addEventListener('click', function(){
wrapperMenu.classList.toggle('open');
})
can be putted on app.component.ts file. or if you have separate component for the header will be better to put the code in its ts file specifically on ngOnInit() hook.
Edit the best hook in component life-cycle is to put this code into ngAfterViewInit() hook.
Edit 2: Another good practice is to used the predefined class menu-content-open that is added automatically when the menu is opened and you can change the selector in your CSS code from .open to menu-content-open
check my forked example from your original one here.
Note the code will work perfect when you add it into the ionic app.

Is it possible to use JQuery includes with Angular Includes?

I am working on an application that utilizes both Jquery and AngularJS includes, however Angular does not seem to execute after Jquery has included a file that has AngularJS markup. Jquery is including the "top_nav.html" template and inside this template there lives a angluar ng-include calling cart.html". I need to figure out how to get the angular code to execute after being included by jQuery.
<div id="topNav"></div>
<script>
//outside the document ready statment
$('#topNav').load('includes/top_nav.html');
<script>
top_nav.html:
<div>
...
<div ng-controller="shoppingCart"
class="shopping-cart"ng-include="'includes/cart.html'"></div>
</div>
The jquery load does an ajax request. When the ajax is resolved, the angular have already been bootstrapped (assuming you use ng-app directive), so the html chunk that have been dynamically loaded was not bootstrapped by angular.
So, I guess that on the callback of the jquery load, you need to manually bootstrap angular passing <div id="topNav"></div> as the context. Something like this:
var topNav = $( "#topNav" );
topNav.load( "includes/top_nav.html", function() {
angular.bootstrap(topNav.find("> div")[0], ['topNavAngularModule']);
});
Note: I'm not sure, sorry, I haven't tested it, but I think it might only work if #topNav is located outside ng-app.

AngularJS 1 include preformated html code from templates

I'm writing a tutorial website for angularjs using angularjs and I have a lot sections of sample code.
So I have a bunch of <pre><html ng-app></html></pre> tags.
I want to put the code samples in a separate files but ng-include doesn't work on <pre></pre> tags. How would I put html code samples in separate files?
Small side question: what would you name the folder of those files? Would ./samples/ work?
I've tried this solution:
https://stackoverflow.com/a/34164921/859082
But it doesn't seem to work because the sample doesn't stay preformatted for newlines and tabs and I don't know why it doesn't work. Here's my attempt using the previous solution:
http://plnkr.co/edit/0nP76Im6XWWCleShsxAR?p=preview
Set CSS white-space: pre-wrap; for your myPre directive.
I forked your plunker, and came up with this plunker here. You could dynamically set the path, which would update the content.
HTML
<body ng-app="app">
<div ng-controller="mainCtrl">
<pre ng-bind="content"></pre>
</div>
</body>
JS
angular
.module('app', [])
.controller('mainCtrl',function($scope,$http,$log){
$http({
method: 'GET',
url: 'common1.html'
}).then(function successCallback(resp) {
$scope.content = resp.data;
}, function errorCallback(response) {
$log.warn('Could not locate file...');
});
});
Additional Plunks:
Allow changing template that is displayed (change index to common1): http://plnkr.co/edit/s5N1nhYQ6SnJ7SVKHVas?p=preview
View page's own code: http://plnkr.co/edit/hJm0b4SQzPTSeRrGmYCx?p=preview
Multiple samples per page: http://plnkr.co/edit/Wtyp6xL1BViicoFUVOSb?p=preview

converting Jquery to angular or making Jquery work in angular

I am new to angular and we are converting a set of screens based on jsp to angular. Initially we have written lot of code in Jquery. Converting them to angular is tedious task and thought of trying to see if we can make jquery work with angular. Here is teh code snippet that i am trying to make it work while it in Jquery.
$(document).ready(function() {
$("#ClickTask2").click(function() {
$(".ClickTask1").hide();
$(".ClickTask2").show();
});
});
Above is the piece of code I have in JQuery and i tried to make it work.
angular.element(document).ready(function() {
$("#ClickTask2").click(function() {
$(".ClickTask1").hide();
$(".ClickTask2").show();
});
});
Can anyone tell me how i could make it work with minimal changes to the above one and rest of the jqueries?
You can convert many jquery features over to Angular by simply changing the $() method to angular.element() e.g.
$('#output').html('<h1>Title</h1>');
You could convert this to:
angular.element('#output').html('<h1>Title</h1>');
However not all function work, and some are renamed e.g.
$("#output").click(function() { console.log('Hi'); });
Would need to be changed to:
angular.element('#output').on('click', function() { console.log('Hi'); });
You can find a full list of the supported functions here:
https://docs.angularjs.org/api/ng/function/angular.element
like said Luis Masuelli on the comments read the basis of Angular. a quick lesson
app.js
function TaskCtrl($scope) {
$scope.selectedTask = null;
$scope.tasks = [/* ... */];
$scope.onClickTask = function(task) {
$scope.selectedTask = task;
}
$scope.isSelected = function (task) {
return task === $scope.seletectedTask;
}
}
$scope it is a special variable, it is injected by Angular to controllers and serves to communicate the controller with the view among other things. A controller can be any function and the name does not matter.
main HTML
<ul data-ng-controller="TaskCtrl">
<li data-ng-repeat="task in tasks" data-ng-click="onClickTask(task)">
{{task.title}}
<div data-ng-show="isSelected(task)">{{task.description}}</div>
</li>
</ul>
data-ng-controller tells to Angular "this is the controller" for this tag and her children. The other directives are pretty explanatory, but the documentation you left it more clearly.
Of course I am assuming that your tasks has the following structure:
{
title: "...",
description: "..."
}
in your html you need include the angular.js, the previous js and a directive to tell angular that this is a application
<!DOCTYPE html>
<html>
<head></head>
<body data-ng-app>
<!-- main HTML -->
<script src="angular.js"><script/>
<script src="app.js"><script/>
</body>
</html>
the data- prefix on each directive is not necessary but as angular "extend" HTML and these are not native attributes, I use them to place custom attributes as "ng-repeat", "ng-controller", "ng-app" etc. They are called directives
Remember, with Angular you need not manipulate the DOM directly as is done with jQuery, except for some special exceptions

Including HTML file in Javascript

I know this is a solved problem and the question might sound stupid but I come from a mostly backend, mobile and low-level development background.
I am working on a JS application (pure JS, no framework but structured really nicely). The only issue with the application is that all HTML is written in Javascript. So it would look like:
$div = ('<div>Hello</div>');
And then you can imagine how ugly this can get with all the additions and HTML manipulations. Now this HTML eventually ends up getting included into an index.html file that has a standard layout that all other JS files will end up exporting their HTML into somehow (uses some PHP). I want to be able to create a separate HTML file, and have a JS file use that file. How can I do so? I know typically the problem is the other way round: in the HTML, get the JS/template it. But in this app's case, this is not the issue.
With the current app I have, is there a way to use Handlebars or Underscore, or anything similar, to be able to write the HTML in an HTML file and just include it into the Javascript? I understand that this may require some pre-compilation but this isn't a problem.
The examples on Underscore and Handlebars only show simple HTML examples written the way I have it above. Examples online are showing how to template HTML with Javascript, but not precisely what I want.
Anyone has any suggestions or can help please?
I think you can easily do this using JQuery's $.ajax() method. Here's an exmaple:
$.ajax({
type: "GET",
url: "/templates/something.html",
dataType: "xml",
success: function (xml) {
$div = xml;
console.log('Loaded HTML: ', xml);
}
});
Handlebars will work for what you're trying to do, and it's super simple to use!
Let's take a simple example (taken from the handlebars website). Assume this is your HTML:
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
All you have to do is put it in a file (let's call it html.handlebars) then reference that file in a script tag:
<script id="html-template" type="text/x-handlebars-template" src="./html.handlebars"/>
Then from your Javascript you can create a template:
var source = $("#html-template").html();
var template = Handlebars.compile(source);
then generate the HTML from the template:
var context = {title: "My New Post", body: "This is my first post!"}
var html = template(context);
at this point html will be:
<div class="entry">
<h1>My New Post</h1>
<div class="body">
This is my first post!
</div>
</div>
which you can use just like any other string of html (ex: $(html).appendTo('body')).
You can make as many handlebars templates as you want, ranging in size from full pages to small snippets as above.
If performance becomes an issue you can look into precompiling as well: http://handlebarsjs.com/precompilation.html

Categories

Resources