I am developing an app using Angularjs and adding HTML using $sce.trustAsHtml() in my page. I want to call a function in above dynamically added content. My html and script as below.
HTML
<div ng-app="ngBindHtmlExample">
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML"></p>
</div>
</div>
Javascript
angular.module('ngBindHtmlExample', ['ngSanitize'])
.controller('ngBindHtmlCtrl', ['$scope','$sce', function ngBindHtmlCtrl($scope, $sce) {
$scope.myHTML =$sce.trustAsHtml(
'I am an <code>HTML</code>string with links! and other <em>stuff</em>');
$scope.removeExp = function (){
console.log('dfdfgdfgdfg');
}
}]);
jsfiddle
Click Here to see
It's a bit tricky because ng-bind-html will simply insert plain old html and not bother compiling it (so any directives in the html will not be processed by angular.
The trick is finding a way to compile whenever the template changes. For example, you could create a directive that does this. It would look something like:
.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
//Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});
You can then use it like this:
<p ng-bind-html="myHTML" compile-template></p>
See the working example here:
http://jsfiddle.net/3J25M/2/
Related
The Situation
Nested within our Angular app is a directive called Page, backed by a controller, which contains a div with an ng-bind-html-unsafe attribute. This is assigned to a $scope var called 'pageContent'. This var gets assigned dynamically generated HTML from a database. When the user flips to the next page, a called to the DB is made, and the pageContent var is set to this new HTML, which gets rendered onscreen through ng-bind-html-unsafe. Here's the code:
Page directive
angular.module('myApp.directives')
.directive('myPage', function ($compile) {
return {
templateUrl: 'page.html',
restrict: 'E',
compile: function compile(element, attrs, transclude) {
// does nothing currently
return {
pre: function preLink(scope, element, attrs, controller) {
// does nothing currently
},
post: function postLink(scope, element, attrs, controller) {
// does nothing currently
}
}
}
};
});
Page directive's template ("page.html" from the templateUrl property above)
<div ng-controller="PageCtrl" >
...
<!-- dynamic page content written into the div below -->
<div ng-bind-html-unsafe="pageContent" >
...
</div>
Page controller
angular.module('myApp')
.controller('PageCtrl', function ($scope) {
$scope.pageContent = '';
$scope.$on( "receivedPageContent", function(event, args) {
console.log( 'new page content received after DB call' );
$scope.pageContent = args.htmlStrFromDB;
});
});
That works. We see the page's HTML from the DB rendered nicely in the browser. When the user flips to the next page, we see the next page's content, and so on. So far so good.
The Problem
The problem here is that we want to have interactive content inside of a page's content. For instance, the HTML may contain a thumbnail image where, when the user clicks on it, Angular should do something awesome, such as displaying a pop-up modal window. I've placed Angular method calls (ng-click) in the HTML strings in our database, but of course Angular isn't going to recognize either method calls or directives unless it somehow parses the HTML string, recognizes them and compiles them.
In our DB
Content for Page 1:
<p>Here's a cool pic of a lion. <img src="lion.png" ng-click="doSomethingAwesone('lion', 'showImage')" > Click on him to see a large image.</p>
Content for Page 2:
<p>Here's a snake. <img src="snake.png" ng-click="doSomethingAwesone('snake', 'playSound')" >Click to make him hiss.</p>
Back in the Page controller, we then add the corresponding $scope function:
Page controller
$scope.doSomethingAwesome = function( id, action ) {
console.log( "Going to do " + action + " with "+ id );
}
I can't figure out how to call that 'doSomethingAwesome' method from within the HTML string from the DB. I realize Angular has to parse the HTML string somehow, but how? I've read vague mumblings about the $compile service, and copied and pasted some examples, but nothing works. Also, most examples show dynamic content only getting set during the linking phase of the directive. We would want Page to stay alive throughout the life of the app. It constantly receives, compiles and displays new content as the user flips through pages.
In an abstract sense, I guess you could say we are trying to dynamically nest chunks of Angular within an Angular app, and need to be able to swap them in and out.
I've read various bits of Angular documentation multiple times, as well as all sorts of blog posts, and JS Fiddled with people's code. I don't know whether I'm completely misunderstanding Angular, or just missing something simple, or maybe I'm slow. In any case, I could use some advice.
ng-bind-html-unsafe only renders the content as HTML. It doesn't bind Angular scope to the resulted DOM. You have to use $compile service for that purpose. I created this plunker to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller's scope. The source is posted below.
demo.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
</body>
</html>
script.js
var app = angular.module('app', []);
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Found in a google discussion group. Works for me.
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$compile(element)($rootScope);
});
You can use
ng-bind-html https://docs.angularjs.org/api/ng/service/$sce
directive to bind html dynamically.
However you have to get the data via $sce service.
Please see the live demo at http://plnkr.co/edit/k4s3Bx
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.getHtml=function(){
return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
}
});
<body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
</body>
Try this below code for binding html through attr
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic);
than element.html(attr.dynamic);
It seems my li elements in angularjs directive not responding clicking event.
HTML:
<my-selbg>
<ul>
<li ng-repeat="bgimage in bgimages"><img src={{bgimage}} width="85" height="82" dir={{bgimage}}></li>
</ul>
</my-selbg>
JS:
var mlwcApp = angular.module('mlwcApp', [])
.controller('BgImagesListController', function($scope, $http) {
$http.get("http://localhost:8080/webcontent/bg_images").success(function(response) {
$scope.bgimages = response;
});
})
.directive('myselbg', function(){
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs){
var elementOne = angular.element(element.children[1]);
var elementTwo = angular.element(element.children[2]);
var elementThree = angular.element(element.children[3]);
setUpBGImg = function(){
console.log('link function');
};
$(elementOne).on('click', setUpBGImg);
$(elementTwo).on('click', setUpBGImg);
$(elementThree).on('click', setUpBGImg);
}
};
});
I have 3 li elements and clicking any of them dose not hit the code in link function. Anyone has idea?
You're new to angular, by the looks of it.
First off, before going any further - your directive will not even bind at all in the state it is in. You've got an element directive (which is fine, though if I were you I'd make it an attribute directive by restricting on A, which allows you to then apply it to the list rather than an element above it) named myselbg in your code. However, your markup is set as my-selbg, which would then look for the angular directive mySelbg, which does not exist.
In addition to this, your directive will evaluate before the list is rendered (thanks to the order of priority in execution). You have two choices to go around this:
You can do something like this: https://jsfiddle.net/a01n3srw/1/ . Really not recommended - I am using $timeout in order to evaluate code after the current refresh cycle is done, at which point the list fully exists
You can use the simple ngClick angular core directive in order to make this easy. Added bonus, when your function that you evaluate starts modifying scope, you won't shoot yourself in the foot using the previous method and having to use $apply
I have an input element and, on DOM ready, I attach to this a jQuery plugin:
<input id="classic-input" type="text">
<script type="text/javascript">
$(document).ready(function () {
$("#classic-input").tokenInput("http://jquery-tokeninput-demo.herokuapp.com/");
});
</script>
This works pretty well and since I need to use this in various part of my application I've created template.html and inserted in it the previous snippet of code, than I created this:
(function() {
'use strict';
angular
.module('app', [])
.directive('myDir', myDir);
function myDir() {
return {
templateUrl : "template.html"
};
}
})();
When I insert this directive in the page the form is shown, but nothing happen when I interact with it. I'm pretty sure that ready handler is the root of all evil. Am I wrong? If I'm right how can edit this directive?
Here is a plunk with examples.
Your template is rather small, besides you could skip script part - just put your code in directive, like this:
function myDir() {
return {
link: function (scope, element) {
$(element).tokenInput("http://jquery-tokeninput-demo.herokuapp.com/");
}
};
}
And apply it to input tag like this:
<input type="text" my-dir>
This way you don't have id hard-coded in your template, which will become a problem in case there multiple such directives on page.
See updated demo.
I have a JSON file that contains the page content I wish to load. In it, I have a link that looks like this:
<a data-ng-click='foo()'>Bar</a>
When I load the page content into the page as HTML:
<p class="body" ng-bind-html="jsonText | raw"></p>
using this filter:
app.filter('raw', function ($sce) {
return function (input) {
return $sce.trustAsHtml(input);
}
});
the link does not trigger foo() call on click. Is what I'm trying to do impossible or am I doing something wrong?
Using filter for this is not a good idea, because you need to $compile the loaded HTML and for that you need $scope. So, you either need to $compile it manually and put the result in $scope yourself, or create a directive instead of a filter:
.directive('dynamicHtml', ['$compile', function ($compile) {
return {
link: function ($scope, $element, $attrs) {
$scope.$watch($attrs.dynamicHtml, function (html) {
$element.empty().append($compile(html)($scope));
});
}
};
}]);
and use it instead of ngBindHtml:
<p dynamic-html="jsonText"></p>
Just be aware that by compiling the HTML yourself, you're completely bypassing contextual escaping, so you should only do it with your own, secure content.
The problem is that your adding a plain text into DOM. Your filter will just ad an piece of html text which includes the ng-click directive which as far as the browser is concerned, it is just an attribute it cannot understand.
You need to compile the template using the $compile service before injecting it into the dom
So long story short, I've tried a billion ways to put a parameter into a string as text, with no solution to be had. I decided that instead I might use a Document.Write to cheat and print a global variable as HTML... However, I discovered that an HTML partial in AngularJS, won't let me use and tags on the partial page.
Example:
$routeProvider
.when('/score', {templateUrl: 'partials/score.html'})
Then, on score.html, I can't put in this statement. It simply does not execute:
<script type="text/javascript">
document.write("This is a test");
//document.write("This is a test"+$rootScope.variable);
</script>
I've also tried window.document.write, even ngApp.document.write. It just doesn't seem to write at all. On network view it looks like the JS isn't running at all. Why? How?
EDIT: I know about data binding. It doesn't work inside an attribute string... I don't know why. This doesn't not work:
<div addthis-toolbox class="addthis_toolbox addthis_default_style addthis_32x32_style social-width" style="width: 150 px">
<a class="addthis_button_twitter" addthis:title="My score is {{score}}"></a>
</div>
EDIT2: Actually, I think that there might be a directive overriding the div class. Here is the angular directive in question:
myApp.directive('addthisToolbox', function() {
return {
restrict: 'A',
transclude: true,
replace: true,
template: '<div ng-transclude></div>',
link: function ($scope, element, attrs) {
// Dynamically init for performance reason
// Safe for multiple calls, only first call will be processed (loaded css/images, popup injected)
// http://support.addthis.com/customer/portal/articles/381263-addthis-client-api#configuration-url
// http://support.addthis.com/customer/portal/articles/381221-optimizing-addthis-performance
addthis.init();
// Ajax load (bind events)
// http://support.addthis.com/customer/portal/articles/381263-addthis-client-api#rendering-js-toolbox
// http://support.addthis.com/customer/portal/questions/548551-help-on-call-back-using-ajax-i-lose-share-buttons
addthis.toolbox($(element).get());
}
}
});
How does one pass data bindings into an attribute if it's got a directive affecting it?