How to compile HTML? - javascript

In controller bind same data like $scope.name = "<div>geetha teko</div>", this name will now binded to html like {{name}}, it is printing like this in browser."<div>geetha tek0</div>", how can get only 'geetha tek0' in browser with html tags.
I tried bellow please help any one.
html code
<div>
<p> my name is: {{name}}</p>
</div>
angularjs
<script>
function MyCtrl($scope) {
$scope.html = "<div> ramesh bogandla</div>"
}
</script>
you can check on jsfiddle:http://jsfiddle.net/ADukg/10127/

I updated your JSFiddle, http://jsfiddle.net/ADukg/10129/.
Use the following:
<span ng-bind-html-unsafe="html"></span>
Or for what you have in your question rather than the JSFiddle you provided:
<p> my name is: <span ng-bind-html-unsafe="html"></span></p>
Here's some further information that might be handy.

Related

compile ng-bind-html inside ng-repeat

I have a special template problem... I have a array of products, every products have a property "button_code", this property is a result in plain text of HTML laravel template with some angular code inside.
Actually im using a ng-bind-html="product.button_code" inside a and use this template inside a ng-repeat, the html code is correctly inserted in every repeat iteration, but the code is plain text, and I need to "wake up" the ng-controllers ng-clicks etc inside this html
I try with this:
var targets = $('.buy-button-container').toArray();
for (var target in targets) {
console.log($(targets[target]));
$compile($(targets[target]))($scope);
}
$scope.$apply();
But this make the code inside the container (all html code inserted in the ng-bind-html) dissapear of the DOM.
How i can do this?
PD: and yes, im forced to use these template in these product.button_code because special things...)
Thanks
EDIT: This is a piece of code i want to bind:
<button class="buy-link btn btn-default" data-toggle="modal" role="button" ng-controller="BuyController" ng-click="doProduct({'id':'8888','title':'testestest','price':13.99,'currency':'EUR''preorder_enabled':false,'crossedPrice':100,'stock':true,'short_desc':'bla bla bla.','lbonus':false,'bonus_txt':false})">
<span class="left">
<i class="fa fa-cart"></i>
<span itemprop="price">€13.99</span>
</span>
<span class="right">
{{GETIT}}</span>
</button>
Use the transclude function furnished as the second argument of the function created by the $compile service:
app.directive("compileBindExpn", function($compile) {
return function linkFn(scope, elem, attrs) {
scope.$watch("::"+attrs.compileBindExpn, function (html) {
var expnLinker = $compile(html);
expnLinker(scope, function transclude(clone) {
elem.empty();
elem.append(clone);
})
});
};
});
The above directive evaluates the compile-bind-expn attribute as an AngularJS expression. It then uses the $compile service to bind the evaluated HTML to the element. Any existing content will be removed.
Usage:
<div class="buy-button-container" compile-bind-expn="buttonCode">
<p>This Node disappears when expression binds</p>
</div>
Note that the directive uses a one-time binding in the $watch to avoid memory leaks.
The DEMO on JSFiddle
In order to make HTML render you have to use the following function:
$sce.trustAsHtml('<b>Your html</b>');
You will have to inject $sce into your Controller.
If you are doing this in a ng-repeat you will need a function in your controller that does this. Ex:
$scope.transformHTML = function(html) {
return $sce.trustAsHtml(html);
}
in your template...
<div ng-repat="foo in bar">
<div ng-bind-html="transformHTML(foo.html)"></div>
</div>
Anyway, I don't think that the "Angular" magic within your HTML will work.

Inserting text into HTML from AngularJS

In my index.html file, I have created a very bare-bones form. I have separated much of the detail into app.js so that if someone wants to have their version of the form look different, they just have to insert a modified copy of app.js (trying to go for portability here).
However, I am very new to AngularJS, which is what a lot of app.js is using. I could use some help please!
Here is a code snippet that I'm having some trouble with:
<body ng-controller="controller">
<div class="page">
<section class="signin">
<form name="form" novalidate>
<div class="intro">
<label ng-model="service-desk-name"></label>
<span ng-bind="service-desk-name"></span>
<label ng-model="welcome"></label>
<span ng-bind="welcome"></span>
</div>
Coupled with:
var app = angular.module('app',[]);
app.controller('controller', ['$scope', function($scope) {
$scope.service-desk-name = 'Arbitrary Service Desk Name';
$scope.welcome =
'Please sign in and a consultant will be with you shortly.';
}]);
Because I may be doing something dreadfully wrong, I'll explain what I want to do. The intro section is displayed above the actual form, showing the service desk name, and some kind of custom welcome or informational message through ng-model="service-desk-name" and ng-model="welcome", respectively. My hope is that I can get the HTML to grab value of these two models that I define in app.js. This way, the HTML doesn't control what is displayed, it just grabs what is defined and displays it.
Right now, these fields are not showing up at all on the webpage, indicating that there's just some kind of syntax error. I'm so new to Angular so I don't really know what to try to fix it from here.
replace
<label ng-model="service-desk-name"></label>
with
<label>{{service-desk-name}}</label>
ng-model means that you want bi-directional binding, and is used for example with inputs, so that when you start typing into the input, the value is stored inside anything that you reference through ng-model, i.e.
<input type="text" ng-model="inputValue" />
will save the input into $scope.inputValue
{{}} means you want to output something from the controller in the view.
Variable name can not have most special character (except _, $) when you are defining directly after a .(dot). This is the reason where controller code is throwing an error, since nothing is getting rendered on page.
You could define that property by specifying key over $scope object like
$scope['service-desk-name'] = 'Arbitrary Service Desk Name';
Additionally the ng-model would work on input element only, but you are using over label. Do below change to welcome as well.
<input ng-model="service-desk-name"/>
But Ideally you shouldn't be define scope variable in such format.
Preferred way would be to use camelCase while defining variables.
Agree with Pankaj Parkar
Also you can't get value in this case because you don't set "ng-app"
plnkr link
var app = angular.module('app', []);
app.controller('myController', function ($scope) {
$scope.serviceDeskName = 'Arbitrary Service Desk Name';
$scope.welcome = 'Please sign in and a consultant will be with you shortly.';
});
<!DOCTYPE html>
<html ng-app="app"> <!-- For example define your app module name here -->
<head>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="myController">
<div class="page">
<section class="signin">
<form name="form" novalidate>
<div class="intro">
<label ng-model="serviceDeskName"></label>
<span ng-bind="serviceDeskName"></span>
<hr>
<label ng-model="welcome"></label>
<span ng-bind="welcome"></span>
</div>
</form>
</section>
</div>
</body>
</html>

Simple angular binding

I did a very little application, but binding not working as model to object. How is it possible?
angular.module("simpleapp", [])
.controller("Controller", ['$scope', function($scope) {
$scope.sample = {};
$scope.sample.input = 4;
}]);
<body ng-app = "simpleapp" >
<input ng-model="sample.input" type="text" value="text" />
<div ng-controller = "Controller"><p>input "{{sample.input}}"</p></div>
</body>
You are using simpleapp in HTML and just app in your JS.
They have to be the same in order to work correctly.
Plus you put the input with the scope variable outside the controller. It should be inside.
For example you can edit your html like this:
<body ng-app="app" ng-controller="Controller">
<!-- other divs here -->
</body>
You have to update your body tag from <body ng-app="app"> and then you have put put your input inside the scope of your controller
<body ng-app="app">
<div ng-controller = "Controller">
<input ng-model="sample.input" type="text" value="text" />
<p>input "{{sample.input}}"</p>
</div>
</body>
The answers by Atul,NV Prasad and fbid are absolutely correct.You can view the DEMO here.
One thing that they have missed out is another way to bind your elements to the angular variable.That is using ng-bind.It is used as follows:
<p ng-bind="sample.input"></p>
What's the difference between ng-bind="sample.input" and
{{sample.input}}?
When you load the page, with the {{}} notation, you will see the curly brackets until the angular content is rendered.In the case of ng-bind, you won't.
For more details:LINK and this answer specifically
Use Proper Angularjs Version Library .You need to Go through Angularjs Doucmentation and Try to Understand by experimenting . That Makes you Strong
Some Beginner Mistakes :-
You Should write all the code after assigning Controller to Html
Element . Otherwise Your Code Don't Work even if it is Correct . You need
to assign a variable to Use.
html Code sample (understand Your mistake by taking look at code or the Below Plunkers :-) :-
<body ng-controller = "sampleController">
<input ng-model="sample.node" type="text" />
<p>input "{{sample.node}}"</p>
<input ng-model="sample1" type="text" />
<p>input "{{sample1}}"</p>
</body>
Controller Coding :-
angular.module("sampleApp", [])
.controller("sampleController", ['$scope', function($scope) {
$scope.sample = {'node':1};
$scope.sample1 = 'my first default value';
}]);
Here we go Simple Binding Example :-
http://jsfiddle.net/cmckeachie/Y8Jg6/
Plunker With Little More Concept of Data binding :-
https://plnkr.co/edit/TmAsSCKQDHfXYEbCGiHW?p=preview
Go through Documentation for some more understanding Good Luck !!

Thinking in AngularJS: characters/tags embedded within text getting mangled

Having trouble wrapping my head around something in Angular. I have a page where I list blog posts (or will, anyway). The posts are stored within a database. Angular gets them from a php script. That's all fine and dandy, but these blogs will understandably have tags (a, img, etc.) embedded in them. Angular doesn't seem to like that.
After searching around here I found an answer two the error produced when my blog posts had newline characters in them (the horror). (white-space: pre-wrap). I'm finding no such love with an embedded tag. Also, having a double quotation mark in a message results in the page not being rendered and an error in the console.
I'm sure this has been asked many times, but the search is only yielding me false positives. :(
EDIT: plunker or jsfiddle will require me to change the model a bit. Let me try this.
Here's the actual code.
<script>
function aboutController($scope,$http) {
var site = "http://onfilm.us";
var page = "/about.php";
$http.get( site + page )
.success(function(response) {
for ( i = 0; i < response.length; i++ ) {
console.log( response[i] )
}
$scope.data = response;
});
}
</script>
</head>
<body>
<script src="header.js"></script>
<div class="centered" style="top: 50px; width: 500px" data-ng-app="" data-ng-controller="aboutController">
<div class="" style="font-family: sans-serif;" data-ng-repeat="item in data">
<div class="text">{{ item.message }}</div>
</div>
</div>
</body>
You can see the output in action here:
http://onfilm.us/about.html
The troubling part would be in this snippit.
taken from Erick Kim's informative website ...
It shows up as string literal w/ the code above... not a link.
You can see the whole data it's reading in here if you want:
http://onfilm.us/about.php
To include html tags in your bindings:
Include angular-sanitize.js in your page:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-sanitize.min.js"></script>
Include the ngSanitized service in your app's dependencies. Do this where you define your module, like so:
angular.module('yourModule', ['ngSanitize'])
Use ng-bind-html to bind your data; so, replace:
<div class="text">{{ item.message }}</div>
with
<div class="text" ng-bind-html="item.message"></div>

Simple AngularJS example with a module and controller in jsFiddle

This probably a combo jsFiddle/Angular question, but I'm trying to learn me some basic Angular and I'm not sure why it only works when I include the controller JS in the HTML pane. jsFiddle here
Basically the following works:
<div ng-app="myAppModule" ng-controller="someController">
<!-- Show the name in the browser -->
<h1>Welcome {{ name }}</h1>
<p>made by : {{userName}}</p>
<!-- Bind the input to the name -->
<input ng-model="name" name="name" placeholder="Enter your name" />
</div>
<script>
var myApp = angular.module('myAppModule', []);
myApp.controller('someController', function($scope) {
// do some stuff here
$scope.userName = "skube";
});
</script>
But if I try to move the JS within the script tag to the JavaScript pane, it fails.
Take a look at this article for some info about jsFiddle with Angular
Also more examples on AngularJS Wiki that you could use:
https://github.com/angular/angular.js/wiki/JsFiddle-Examples

Categories