angular how to let html redner the scope variable as a string - javascript

Say I have the following line in a controller hmmCtrl:
$rootScope.value = 1;
$scope.hmm = "{{$root.value}}"
And in html, if I have:
<section ng-controller="hmmCtrl">
{{hmm}}
</section>
Currently it displays:
{{$root.value}}
but I actually want to see the value of $root.value:
1
In the long run I plan to put the $root.value in a json file that is going to be parsed by the hmmCtrl.
How can I make this happen?

So what you can do is, you can write a inside a controller which can return your interpolation expression evaluated value
Code
//inject `$interpolate` inside controller function before using it.
$scope.evaluateValue = function(expr){
return $interpolate(expr)($scope);
}
Markup
<section ng-controller="hmmCtrl">
{{evaluateValue(hmm)}}
</section>
Other way
<section ng-controller="hmmCtrl" ng-bind="evaluateValue(hmm)">
</section>
Demo Here

Change your html-Code from
<section ng-controller="hmmCtrl">
{{hmm}}
</section>
to
<section ng-controller="hmmCtrl">
{{value}}
</section>
$scope inherites from $rootScope, meaning $scope also has the "value"-variable...

Related

How to compile HTML?

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.

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.

How to print to console.log from inside Angular.js inline-template's script tag?

I'm trying out the inline-template of Angular.js. I would like to have a way to debug Angular objects by printing to the console whenever an html page is rendered.
The inline-template puts html templates inside script tags. For example:
<script type="text/ng-template" id="/htmlpage.html">
<div class="page-header">
<h1>Title</h1>
</div>
<!-- everything else here is html too -->
</script>
It's tricky because the stuff inside the script tags is not really JavaScript anymore. So I don't know how to printing to the console inside the htmlpage.html with inline-template.
I have tried but failed with nesting a script tag:
<script type="text/ng-template" id="/htmlpage.html">
<!-- html page template Angular stuff before is okay -->
<script>console.log("this line DOESN'T SHOW UP anywhere");</script>
<!-- html page template Angular stuff AFTERWARDS ALL FAIL-->
</script>
I also tried just throwing in a bare console.log, since it's inside a script tag.
<script type="text/ng-template" id="/htmlpage.html">
<!-- rest of html page template is okay -->
console.log("this entire line gets output as text on the html page");
<!-- rest of html page template is okay -->
</script>
but the entire line, console.log("this entire line gets output as text on the html page");, gets printed out to the html page, not the console!
You can achieve this by calling some debugging function defined in the controller scope with ng-init in the template definition. See this example.
Let's say the template is defined by
<script type="text/ng-template" id="myTemplate.html">
<div ng-init="log('In template: '+$index)">{{greet}} Melissa<div>
</script>
and you have a controller defined as
var app = angular.module('myApp', [])
.controller('myController', ['$scope', '$log', function($scope, $log) {
$scope.greetings = ["Hello", "Bonjour", "Guten tag"];
$scope.log = function(message) {
$log.debug(message);
}
}]);
then
<ul ng-controller="myController">
<li ng-repeat="greet in greetings">
<div ng-include src="'myTemplate.html'"></div>
</li>
</ul>
should print in the console
In template: 0
In template: 1
In template: 2
The ng-init is called each time a template is instantiated. I just log some values available in the scope, like $index which is the index in the ng-repeat loop.
See this example.
Using the above answer, I found the following simpler.
The easiest solution for me was to temporarily set $scope.console = console in my controller, letting the template have access to the window.console global variable and its associated functions as normal, through the $scope binding
Because the templates are tightly scoped, they do not have access to global and window variables, as a result console.X() is not available from the template. And, like you probably experienced, attempting to reference undefined values from within the template did not result in an error, just... nothing. (Cue tearing hair out trying to figure out why events aren't firing)

angularJs variable to Html [duplicate]

This question already has answers here:
Insert HTML into view from AngularJS controller
(17 answers)
Closed 7 years ago.
Actually im searching about how i can transform my variable into Html, this variable contain a embed code from instagram.
in my controller
instaembed.controler "instaCtrl", ($scope, $http) ->
#instagram embed get example from insta
$http.get ("http://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN/")
.success(data) ->
$scope.html = data.html
...
the result in $scope.html contain a blockquote with many div and image
i've tested it in the view (with ngsanitize), but it show only the text and not the image.
Anyone have an idea about how to get it ? :D
thank you (sorry for my english).
You will have to use Angular's built in Strict Contextual Escaping $sce
$sce Documentation
Then, in your controller:
instaembed.controler "instaCtrl", ($scope, $http, $sce) ->
#instagram embed get example from insta
$http.get ("http://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN/")
.success(data) ->
$scope.html = $sce.trustAsHtml(data.html);
...
You need to use ngBindHtml directive.
https://docs.angularjs.org/api/ng/directive/ngBindHtml
<div ng-bind-html-unsafe="html"></div>
Where html is your $scope.html variable. This will render inside div what your variable contains.
function testCtrl($scope) {
$scope.html = "<strong>Hello world!</strong>"
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-controller="testCtrl" ng-app>
<div ng-bind-html-unsafe="html"></div>
</div>
You should use ng-bind-html
<span ng-bind-html="your scope variable"></span>

Angularjs on page load call function

I am learning AngularJS. I have some article tag and on clicking on a button each article page is showed without any page refresh. This is one page website. What I want is that when article id "showSelector" is loaded I want to call myFunction() and in this function I want to show an alert. But the alert is not showing.
How can I do that?
<article id="showSelector" class="panel" ng-controller="CinemaCtrl" onload="myFunction()">
<header>
<a ng-click="back()" class="icon fa-arrow-circle-left"></a><h2>Shows in {{getSelectedCinema()}}</h2>
</header>
<p>
These shows are played in our single room theatre. Select one to reserce a ticket for it.
</p>
<section>
<div class="row">
<div class="4u" ng-repeat="show in shows">
<div class="movieCard">
<a ng-click="selectShow(show)"></a>
<h3>{{show.nameOfShow}}</h3>
<h4>{{show.timeOfShow | date:'MMM d'}}</h4>
<h4>{{show.timeOfShow | date:'HH:mm'}}</h4>
<p>Free seats: {{show.reservations | freeSeatFilter}}</p>
</div>
</div>
</div>
</section>
<script>
function myFunction() {
alert("Page is loaded");
};
</script>
</article>
You should call this function from the controller.
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.
Obviously better still declare the function in the controller too.
Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).
Instead of using onload, use Angular's ng-init.
<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">
Note: This requires that myFunction is a property of the CinemaCtrl scope.
<section ng-controller="testController as ctrl" class="test_cls" data-ng-init="fn_load()">
$scope.fn_load = function () {
console.log("page load")
};
It's not the angular way, remove the function from html body and use it in controller, or use
angular.element(document).ready
More details are available here: https://stackoverflow.com/a/18646795/4301583
you can also use the below code.
function activateController(){
console.log('HELLO WORLD');
}
$scope.$on('$viewContentLoaded', function ($evt, data) {
activateController();
});
you can use it directly with $scope instance
$scope.init=function()
{
console.log("entered");
data={};
/*do whatever you want such as initialising scope variable,
using $http instance etcc..*/
}
//simple call init function on controller
$scope.init();
var someVr= element[0].querySelector('#showSelector');
myfunction(){
alert("hi");
}
angular.element(someVr).ready(function () {
myfunction();
});
This will do the job.

Categories