ng-include with a variable for src - javascript

I would like to change the ng-includes src with a variable. Currently this is what I have.
<div class='alignRightCenter' id='rightContent'>
<ng-include src="'{{view}}'"> </ng-include>
</div>
And here is the controller:
ctrl.controller('contentCtrl', ['$scope', function($scope) {
$scope.view = "partials/setListName.tpl.html";
}]);
Unfortunately I can not use a ng-view because it is already being used to get me to this page.
Is it possible to make something like this work?

Try as follows:
<ng-include src="view"> </ng-include>
-----------------OR----------------------
You can do this way,
View:
<div data-ng-include data-ng-src="getPartial()"></div>
Controller:
function AppCtrl ($scope) {
$scope.getPartial = function () {
return 'partials/issues.html';
}
}

Like this. You need to use single quotes and +, like you would in JavaScript.
<ng-include src="'/path/to/template'+ my.variable +'.html'"></ng-include>

Related

AngularJS - Convert JSON string into HTML codes [duplicate]

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?
This comes from a requirement to turn an inconsistent JSON blob into a nested list of id: value pairs. Therefore the HTML is created in the controller and I am now looking to display it.
I have created a model property, but cannot render this in the view without it just printing the HTML.
Update
It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.
Example controller :
var SomeController = function () {
this.customHtml = '<ul><li>render me please</li></ul>';
}
Example view :
<div ng:bind="customHtml"></div>
Gives :
<div>
"<ul><li>render me please</li></ul>"
</div>
For Angular 1.x, use ng-bind-html in the HTML:
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that.
$sce
Use $sce.trustAsHtml() in the controller to convert the html string.
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize
There are 2 steps:
include the angular-sanitize.min.js resource, i.e.:
<script src="lib/angular/angular-sanitize.min.js"></script>
In a js file (controller or usually app.js), include ngSanitize, i.e.:
angular.module('myApp', ['myApp.filters', 'myApp.services',
'myApp.directives', 'ngSanitize'])
You can also create a filter like so:
var app = angular.module("demoApp", ['ngResource']);
app.filter("trust", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
Then in the view
<div ng-bind-html="trusted_html_variable | trust"></div>
Note: This filter trusts any and all html passed to it, and could present an XSS vulnerability if variables with user input are passed to it.
Angular JS shows HTML within the tag
The solution provided in the above link worked for me, none of the options on this thread did. For anyone looking for the same thing with AngularJS version 1.2.9
Here's a copy:
Ok I found solution for this:
JS:
$scope.renderHtml = function(html_code)
{
return $sce.trustAsHtml(html_code);
};
HTML:
<p ng-bind-html="renderHtml(value.button)"></p>
EDIT:
Here's the set up:
JS file:
angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
function ($scope, $http, $sce) {
$scope.renderHtml = function (htmlCode) {
return $sce.trustAsHtml(htmlCode);
};
$scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>';
}]);
HTML file:
<div ng-controller="MyController">
<div ng-bind-html="renderHtml(body)"></div>
</div>
Fortunately, you don't need any fancy filters or unsafe methods to avoid that error message. This is the complete implementation to properly output HTML markup in a view in the intended and safe way.
The sanitize module must be included after Angular:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.js"></script>
Then, the module must be loaded:
angular.module('app', [
'ngSanitize'
]);
This will allow you to include markup in a string from a controller, directive, etc:
scope.message = "<strong>42</strong> is the <em>answer</em>.";
Finally, in a template, it must be output like so:
<p ng-bind-html="message"></p>
Which will produce the expected output: 42 is the answer.
I have tried today, the only way I found was this
<div ng-bind-html-unsafe="expression"></div>
ng-bind-html-unsafe no longer works.
This is the shortest way:
Create a filter:
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
And in your view:
<div ng-bind-html="customHtml | unsafe"></div>
P.S. This method doesn't require you to include the ngSanitize module.
on html
<div ng-controller="myAppController as myCtrl">
<div ng-bind-html-unsafe="myCtrl.comment.msg"></div>
OR
<div ng-bind-html="myCtrl.comment.msg"></div
on controller
mySceApp.controller("myAppController", function myAppController( $sce) {
this.myCtrl.comment.msg = $sce.trustAsHtml(html);
works also with $scope.comment.msg = $sce.trustAsHtml(html);
I found that using ng-sanitize did not allow me to add ng-click in the html.
To solve this I added a directive. Like this:
app.directive('htmldiv', function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, element, attr) {
scope.$watch(attr.content, function() {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
});
And this is the HTML:
<htmldiv content="theContent"></htmldiv>
Good luck.
Just did this using ngBindHtml by following angular(v1.4) docs,
<div ng-bind-html="expression"></div>
and expression can be "<ul><li>render me please</li></ul>"
Make sure you include ngSanitize in the module's dependencies.
Then it should work fine.
Another solution, very similar to blrbr's except using a scoped attribute is:
angular.module('app')
.directive('renderHtml', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
html: '='
},
link: function postLink(scope, element, attrs) {
function appendHtml() {
if(scope.html) {
var newElement = angular.element(scope.html);
$compile(newElement)(scope);
element.append(newElement);
}
}
scope.$watch(function() { return scope.html }, appendHtml);
}
};
}]);
And then
<render-html html="htmlAsString"></render-html>
Note you may replace element.append() with element.replaceWith()
there is one more solution for this problem using creating new attribute or directives in angular.
product-specs.html
<h4>Specs</h4>
<ul class="list-unstyled">
<li>
<strong>Shine</strong>
: {{product.shine}}</li>
<li>
<strong>Faces</strong>
: {{product.faces}}</li>
<li>
<strong>Rarity</strong>
: {{product.rarity}}</li>
<li>
<strong>Color</strong>
: {{product.color}}</li>
</ul>
app.js
(function() {
var app = angular.module('gemStore', []);
app.directive(" <div ng-show="tab.isSet(2)" product-specs>", function() {
return {
restrict: 'E',
templateUrl: "product-specs.html"
};
});
index.html
<div>
<product-specs> </product-specs>//it will load product-specs.html file here.
</div>
or
<div product-specs>//it will add product-specs.html file
or
<div ng-include="product-description.html"></div>
https://docs.angularjs.org/guide/directive
you can also use ng-include.
<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>
you can use "ng-show" to show hide this template data.
here is the solution make a filter like this
.filter('trusted',
function($sce) {
return function(ss) {
return $sce.trustAsHtml(ss)
};
}
)
and apply this as a filter to the ng-bind-html like
<div ng-bind-html="code | trusted">
and thank to Ruben Decrop
Use
<div ng-bind-html="customHtml"></div>
and
angular.module('MyApp', ['ngSanitize']);
For that, you need to include angular-sanitize.js,
for example in your html-file with
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-sanitize.js"></script>
Here's a simple (and unsafe) bind-as-html directive, without the need for ngSanitize:
myModule.directive('bindAsHtml', function () {
return {
link: function (scope, element, attributes) {
element.html(scope.$eval(attributes.bindAsHtml));
}
};
});
Note that this will open up for security issues, if binding untrusted content.
Use like so:
<div bind-as-html="someHtmlInScope"></div>
Working example with pipe to display html in template with Angular 4.
1.Crated Pipe escape-html.pipe.ts
`
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
constructor(private sanitizer : DomSanitizer){
}
transform(content){
return this.sanitizer.bypassSecurityTrustHtml(content);
}
}
`
2. Register pipe to app.module.ts
import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
declarations: [...,EscapeHtmlPipe]
Use in your template
<div class="demoPipe" [innerHtml]="getDivHtml(obj.header) | keepHtml">
getDivHtml() { //can return html as per requirement}
Please add appropriate implementation for getDivHtml in associated component.ts file.
Just simple use [innerHTML], like below:
<div [innerHTML]="htmlString"></div>
Before you needed to use ng-bind-html...

Adding a JS Variable to a AngularJS Directory?

I can't seem to get the following code to work:
<script>alert(topic);</script> <!-- Outputs: "dynamics" -->
<div ng-include="'content/' + topic + '.html'"></div> <!-- Does not work. -->
I have deduced the variable is the problem as the following code does work:
<div ng-include="'content/' + 'dynamics' + '.html'"></div> <!-- Works. -->
Does anybody know how I can do this?
Update:
Following Steffen's link, I have written the following code, but still no luck:
<script>
alert(topic); // Outputs "dynamics"
var app = angular.module('myapp', []);
app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
$scope.topic = $window.topic;
}]);
</script>
<div ng-app="myapp" ng-controller="MainCtrl" ng-include="'content/' +
topic + '.html'"></div> <!-- Does not work. -->
Thanks.
Based on Steffen's jsfiddle, here is how I passed a JavaScript variable to AngularJS and used it in defining a directory:
<script>
// Create module.
var app = angular.module('app', []);
// Add controller to module.
app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
$scope.topic = $window.topic;
console.log($scope.topic);
}]);
</script>
<div ng-app="app" ng-controller="MainCtrl" ng-include="'content/' +
topic + '.html'"></div> <!-- Works! -->
Many thanks to all for their answers. :)
try this :
<div ng-include="'content/{{topic}}.html'"></div>
In angularjs , scope variable are access in HTML using The double curly brace notation {{ }} .
Try as follows:
<ng-include src="topic"> </ng-include>
Make sure you have define $scope.topic = "whateveryouwant";
-----------OR-----------
You could do it like:
<ng-include src="getTopic()"></ng-include>
Controller:
function AppCtrl ($scope) {
$scope.getTopic= function () {
return 'partials/whatever.html';
}
}

Getting controller name from $parent in AngularJS

I have converted one of my Angular controllers to Controller As syntax, but I am having trouble getting an ng-grid template to play nicely.
The controller has a function called edit user that looks like this
self.editUser = function (user_data) {
var modalInstance = $modal.open({
templateUrl: '/admin/views/adminuser.html',
controller: 'AdminUserController',
resolve: {
user_data: function () {
return user_data;
}
}
});
modalInstance.result.then(function () {
self.myQueryData.refresh = !self.myQueryData.refresh;
});
};
the ng-grid template looks like this
<div class="ngCellText" ng-class="col.colIndex()">
<a ng-click="$parent.$parent.$parent.$parent.editUser({user_id:row.entity.id, first_name:row.entity.first_name, last_name:row.entity.last_name, email:row.entity.email})">
<span ng-cell-text translate>Edit</span>
</a>
</div>
and my route looks like this
.when('/admin/settings', {
templateUrl: '/admin/views/settings.html',
controller: 'SettingsController as sc',
})
So the problem is in the template when I call
$parent.$parent.$parent.$parent.editUser
it doesn't know what I am talking about unless I include the controller name like
$parent.$parent.$parent.$parent.sc.editUser,
then it works great. However I don't want to bind this template directly to the sc controller. How can I call the editUser without using the controller name?
I was hoping there would be a function on the $parent that would supply the function name like
$parent.$parent.$parent.$parent.getController().editUser
Any suggestions?
You can call functions on parent scope directly without referring to $parent. Because you might get in to trouble later when you modify your view structure.
example:
<div ng-app="MyApp">
<div ng-controller="MyController">
{{myMessage}}
<div ng-controller="MyController2">
<div ng-controller="MyController3">
<div ng-controller="MyController4">
<button id="myButton" ng-click="setMessage('second')">Press</button>
</div>
</div>
</div>
<script>
angular.module('MyApp', [])
.controller('MyController', function($scope) {
$scope.myMessage = "First";
$scope.setMessage = function(msg) {
$scope.myMessage = msg;
};
}).controller('MyController2', function($scope) {
}).controller('MyController3', function($scope) {
}).controller('MyController4', function($scope) {
});
</script>
</div>
</div>
Or else you can use angular $broadcast
Since you are using controllerAs syntax, you can address your controller by the alias, so the actual template line will look like this:
<a ng-click="sc.editUser({user_id:row.entity.id, first_name:row.entity.first_name, last_name:row.entity.last_name, email:row.entity.email})">

How to render HTML Tags from ngModel?

I'm using AngularJS for binding JS variables to my HTML content, and it works fine.
JS
var app = angular.module("Tabs", [])
.controller("TabsController", ['$scope', function($scope){
$scope.events = my_JS_object;
})
HTML
<div>{{events.test}}</div>
It works as long as my_JS_object.test is a simple string, like "Hello World", but once I try to put HTML tag in there, such as Hello <b>World</b> It doesn't use the tags as HTML elements, but as simple text. Which makes sense, only I have no idea how to make the HTML tags work.
As stated by Angular documentation, you can use inbuilt ng-bind-html directive to evaluate model string and insert resulting HTML into element.
Example:
If you have model value like:
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'links! and other <em>stuff</em>';
Use ng-bind-html like:
<p ng-bind-html="myHTML"></p>
For detailed information go through: https://docs.angularjs.org/api/ng/directive/ngBindHtml
Note: Don't forget to inject ngSanitize service in your app.
You need to use the ngBindHtml directive that properly evaluates the expression and inserts the resulting HTML into the element in a secure way. To do this, you must include a reference to angular-sanitize.js in your HTML and then in your angular module, inject ngSanitize.
Like so
var app = angular.module("Tabs", ['ngSanitize'])
.controller("TabsController", ['$scope', function($scope){
$scope.events = my_JS_object;
})
<div ng-controller="TabsController">
<div ng-bind-html="events.test"></div>
</div>
Here is a full working example:
(function(angular) {
'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML = 'Hello This is <b>BOLD<b/>';
}]);
})(window.angular);
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-sanitize.js"></script>
</head>
<body ng-app="bindHtmlExample">
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</body>
Refer to the official angular documentation for details:
https://docs.angularjs.org/api/ng/directive/ngBindHtml
If you want to insert HTML into page you shouldn't do it this way.
There is sanitize for this task.
For example in your controller:
$scope.trustedHtml = "<b>Hello World</b>"
And in your html:
<div ng-bind-html="trustedHtml "></div>
Always check html if using a user given text before inserting.
Also don't forget to add ngSanitize as dependency while creating controller
It's easier to use transclusion if you want to embed custom HTML into your DOM tree.
angular.module('myApp', [])
.controller('MainCtrl', function ($scope) {
$scope.overwrite = false;
$scope.origin = 'parent controller';
})
.directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'my-directive.html',
scope: {},
transclude: true,
link: function (scope) {
scope.overwrite = !!scope.origin;
scope.origin = 'link function';
}
};
});
<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<my-directive>
<p>HTML template</p>
<p>Scope from {{origin}}</p>
<p>Overwritten? {{overwrite}}</p>
</my-directive>
</div>
<script type="text/ng-template" id="my-directive.html">
<ng-transclude></ng-transclude>
<hr />
<p>Directive template</p>
<p>Scope from {{origin}}</p>
<p>Overwritten? {{overwrite}}</p>
</script>
</div>

How to display or any raw html in angular data?

How can I display as space not as string. Is there raw filter like in twig?
<div>{{item}}</div>
$scope.item = ' ';
But the result is escaped &nbsp;. I need this because ' ' have height of 0.
It can be easily done by using ngBindHtml
For Angular above 1.2.x version:
use ng-bind-html
Working Demo
html
<div ng-app='myApp' ng-controller="Controller">
<div ng-bind-html="item"></div>
</div>
script
var app = angular.module('myApp', ['ngSanitize']);
app.controller('Controller', function ($scope, $sce) {
$scope.item = 'What Is Your Name?';
});
For Angular 1.0.x version:
Working Demo
use ng-bind-html-unsafe
html
<div ng-app='myApp' ng-controller="Controller">
<div ng-bind-html-unsafe="item"></div>
</div>
script
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope) {
$scope.item = 'What Is Your Name?';
});
For Angular 1.3.x version:
Use the $sce service to mark the string as safe to use in a specific context (HTML in this case).
See the documentation here
HTML code:
<div ng-app='myApp' ng-controller="Controller">
<div ng-bind-html="item"></div>
</div>
JS code (controller):
var app = angular.module('myApp', []);
app.controller('Controller', function ($scope, $sce) {
$scope.item = $sce.trustAsHtml('<span>Some HTML code</span>');
});
Try using ngBindHtml
<div data-ng-bind-html="item"></div>
You can also create a filter for that.
Filter
app.filter("trustHtmlContent", ['$sce', $sce => htmlCode => $sce.trustAsHtml(htmlCode)]);
usage
<ANY ng-bind-html="value | trustHtmlContent"></ANY>
src: How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+
You can use the ascii code for &nbsp in a string.
Alt-255.
This will correctly render as an &nbsp.

Categories

Resources