How to Display value of dynamically created varible using AngularJS - html

My HTML template code is:
<p>{{"fieldname_"+lang}}</p>
In the controller I have the following:
$scope.lang = "mr";
$scope.fieldname_mr = "Dynamic varible";
I want the result to be Dynamic varible, but it is fieldname_mr.
How can I achieve that?

You can use bracket notation to achieve this:
angular.module('app', [])
.controller('testController',
function testController($scope) {
$scope.lang = "mr";
$scope.dynamicVars = {fieldname_mr : "Dynamic varible"};
});
<body ng-app="app">
<div class="table-responsive" ng-controller="testController">
{{dynamicVars["fieldname_" + lang]}}
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

that you wnt is not able, i made a middleware solution that mantains all your needed but passed by a function that made the return of var, understand that angular force to made like this
<div ng-controller="MyCtrl">
<span ng-init="">{{getValue('fieldname_'+lang)}}</span>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.lang = "mr"; $scope.fieldname_mr = "Dynamic varible";
$scope.getValue =function(name){
return $scope[name] ||'no existe man';
}
}

Yes you can do it like you set your dynamic variable in angular as follow:
what you want variable name store in variable than follow code:
$scope[dynamic_var]=Value of variable;
when you fetch this value as like:
Use this when you not fix property of scope
alert($scope[dynamic_var])
use when you have fix property name
alert($scope.dynamic_var)

Related

Dynamic pass value in a Play2 scala template

I try to dynamically change value of its variable. Once onclick (Change Ticket ID ) button then execute onClickSendEmail and variable value should be change of tickedId.
Its unable to update with newTickedId. I tried while create variable using #defining and individual calling by function also.
So, Basically I got stuck. how it will be solve.
#(sender: String)
<!--#{var tickedId = "tickedId"}-->
#defining(sender.contains("#")) {isEmail =>
#main((if(isEmail) "Email" else "Chat") + " Messages - " + sender) {
...
...
...
<div>
<a onclick="onClickSendEmail();return false;">
Change Ticket ID
</a>
</div>
#defining("getTicketId()") { tickedId =>
#views.html.common.form.panel("Reply",controllers.routes.ChatMessageController.sendEmail(tickedId,sender),"Send"){
<textarea id="emailArea" cols="100" rows="4" name="emailArea"></textarea>
}
<script type="text/javascript">
function onClickSendEmail() {
tickedId= "NewUpdatedTicketId";
}
function getTicketId() {
return "NewUpdatedTicketId";
}
</script>
}
}
}
You should not mix Twirl templating with Javascript. It's a bad approach.
The role for Twirl is to render HTML blocks. You can define conditions and variables here in order to dynamically change the HTML output. While with Javascript you can modify this rendered HTML output without reloading the page.
There are cases where you need to use a Twirl variable in Javascript, then you can do something like:
#(chartData: Html)
<script>
let jsData = #twirlData; // where twirlData is an existing variable
console.log(jsData)
</script>
Here's a link where you can read more.

How can I use ng-bind-html inside my directive?

I'm using templates based on my JSON. So, I can't really use my ng-bind-html like I would normally do.
Seems like the only option I have is to use my sanitized html inside an directive.
Looking for similar questions, I couldn't figure it out how to apply in my case.
Yes, I am pretty newbie into angular.
I'm currently receiving this data from my controller:
$scope.safecontainers = $sanitize($scope.containersmsg);
In my html would normally be like this:
<p ng-bind-html="containersmsg"></p>
But I don't want this, I need to use this ng-bind-html inside a directive!
Some people have talked about $compile, but I couldn't really figure it out how to apply in my case.
EDIT:
Based on comments, i'll add more code to help you guys further understand my goal.
Inside my index.html I'm declaring the controllers needed and calling my
<ng-view></ng-view>
Then, based on what I receive, i'll load one view or another:
<div ng-if='setores[0].SetorTema == "1"'>
<theme-one titulo="{{setores[0].SetorNome}}" logo="
{{setores[0].SetorLogo}}" evento="{{evento[0].EventoNome}}">
</theme-one>
// I omitted some of the parameters because they ain't relevant
</div>
My template is like this: (Just a little part of it to avoid much useless code)
<section class="target">
<div class="col-md-6 col-xs-12">
<div class="" ng-repeat="banner in title">
<div class="target-title">{{ banner.BannerLevelTitulo }}
</div>
<div class="target-desc">{{banner.BannerLevelDescricao}}</div>
</div>
</div>
<div class="col-md-6 col-xs-hidden">
<div class="target-image"><img ng-src="{{targetimage}}" alt="">
</div>
</div>
</section>
This is the controller I want my sanitized code.
hotsite.controller('containerController', function($scope, $http, $sanitize)
{
$scope.containers = [];
$scope.containersmsg = '';
$scope.safecontainers = $sanitize($scope.containersmsg);
$http.get('/Admin/rest/getContainer')
.then(function onSuccess(response) {
var data = response.data;
$scope.containers = data;
$scope.containers = response.data.filter(containers =>
containers.ContainerAtivo);
$scope.containersmsg = $scope.containers[0].ContainerDesc;
})
.catch(function onError(response) {
var data = response.data;
console.log(data);
});
});
This is a piece of my directive:
angular.module('hotsiteDirectives', [])
.directive('themeOne', function($compile) {
var ddo = {};
ddo.restrict = "AE";
ddo.transclude = true;
ddo.scope = {
titulo: '#',
...
(a lot of other scope's)
contimg: '#'
};
ddo.templateUrl = 'app/directives/theme-one.html';
return ddo;
})
And yes, I am calling the ngSanitize
var hotsite = angular.module('hotsite',['ngRoute', 'hotsiteDirectives',
'ngSanitize']);
TL;DR
This is how my code looks like inside a directive, with raw html and not rendered:
This is how it works with ng-bind-html, formatted html
If I do put this inside my view
<p ng-bind-html="containersmsg"></p>
It will be alright, all of it working like it should.
BUT, I need to call this only inside my directive, and I don't know how to do it.
So, with this context:
How can I put my sanitized html inside my directive and template?
You don't even have to trust the html to render it using ngBindHtml because the directive already does it for you. You basically need to create a parameter attribute for your directive to hold the html string, so, inside the directive's template, you use ng-bind-html="myParam".
The following snippet implements a simple demonstration of creating a directive that receives and renders an html input parameter that comes from a controller.
angular.module('app', ['ngSanitize'])
.controller('AppCtrl', function($scope) {
$scope.myHtml = '<div><b>Hello!</b> I\'m an <i>html string</i> being rendered dynamicalli by <code>ngBindHtml</code></div>';
})
.directive('myDirective', function() {
return {
template: '<hr><div ng-bind-html="html"></div><hr>',
scope: {
html: '='
}
};
});
<div ng-app="app" ng-controller="AppCtrl">
<my-directive html="myHtml"></my-directive>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-sanitize.js"></script>

ng-bind-html not working with my $scope.variable

I am trying to add something like dynamic HTML using ng-bind-html but its not working with $scope variable
Here is my Angular code
1)My controller
$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Also that my string is dynamic
"<div><table class=" + "\"table table - bordered table - responsive table - hover add - lineheight table_scroll\"" + "><thead><tr><td>Name</td><td>Age</td></tr></thead><tbody><tr ng-repeat=" + "\"tr in dyna\"" + "><td>{{tr.name}}</td><td>{{tr.age}}</td></tr></tbody></table></div>"
So i cant replace every variable with $scope
2)- My HTML
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>
I got this output
{{name}}
My expected output is
Parshuram
Please can anyone help i am stuck at this point,does that $sce does not bind scope variable?? ..
I've created a working plnkr here: https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview
the problem is that ng-bind-html is not bound to the scope.
you should manually compile the content.
a valid and reusable solution should be creating a directive, whitout using any external modules.
function compileTemplate($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope);
});
}
}
}
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml" compile-template></div>
</div>
ng-bind-html does what it says on the tin: it binds html. It doesn't bind angular template code into your dom.
You need to do this instead:
$scope.thisCanBeusedInsideNgBindHtml =
$sce.trustAsHtml("<div>"+$sanitize(name)+"</div>");
To do this you'll want to include the module ngSanitize from the javascript angular-sanitize.js. See https://docs.angularjs.org/api/ngSanitize
If you want to insert some html that includes angular directives then you should write your own custom directive to do it.
In your html just use
{{name}}
The {{var}} notation is to be used in the HTML code to evaluate that variable.
You can do :
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml('<div ng-bind="name"></div>');
Sorry I make another answer.
If you have
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Then you can do
var str = "<div>{{name}}</div>";
var output = str.replace('{{name}}', $scope.name);
It seems to be the only option.

Angular.js Directive to display in bold a piece of the string

I have a table in angular that is displayed this way:
<table class="row">
<tr ng-repeat="x in myWelcome | filter :search">
<td>{{$index}}</td>
<td>{{x._id}}</td>
<td>{{x.email}}</td>
<td ng-bold-number>{{x.phone}}</td>
<td>{{x.latitude}}</td>
<td>{{x.longitude}}</td>
<td><input type="button" value="Remove" ng-click="removeRow(x._id)"/></td>
</tr>
</table>
The phone column is displayed like this : +1(210)22158765.
I want to create a directive "ng-bold-number" so that the number inside the parenthesis (that is 210 here) would be displayed in bold style like this +1(210)22158765
So I made this directive in Angular :
app.directive('ngBoldNumber', [function() {
return {
restrict: 'A',
link: function($scope, iElement, iAttrs) {
var x = $scope.x.phone.substring(0, $scope.x.phone.indexOf('(')+1)
var y = $scope.x.phone.substring($scope.x.phone.indexOf('(')+1, $scope.x.phone.indexOf(')')+1)
$scope.x.phone=x+y;
}
};
}])
which I am able to cut down the string but I didn't find a way to display it in bold. Can you help me please?
Suppose you would want to go with a directive, you can do it like this : check my plunker here
the directive function itself looks like this:
function boldNumber(){
return {
restrict:"A",
template:"{{pre}} <b>{{bold}}</b> {{post}} ",
replace:false,
scope:{
inBold:"#"
},
link: function(scope, element, attr){
console.log(scope.inBold);
scope.pre = scope.inBold.substring(0, scope.inBold.indexOf('(')+1);
scope.bold = scope.inBold.substring(scope.inBold.indexOf('(')+1, scope.inBold.indexOf(')')+1);
scope.post = scope.inBold.substring(scope.inBold.indexOf(')')+1);
}
};
Basically, what I have added is a template, showing the cuts you made. I had to make one more cut (the final part after the closing ')' ). You have to set replace: false, so your template is appended into the directive element.
Then i have an isolated scope, containing the text that needs to be cut, the phone number. I did simplify the example in my plunker a bit.
The html looks like this then:
<table class="row">
<tr>
<td bold-number in-bold="{{x.phone}}">tryout</td>
<td><input type="button" value="Remove" ng-click="removeRow(x._id)"/></td>
</tr>
</table>
as you can see, the attribute in-bold contains the value for the isolated scope in the directive function. if you need more information, or if something is not clear, please ask.
EDIT: the part about inBold:"#"
in your directive function, when u add the option 'scope', you create a scope that only counts for the directive. The directive itself can no longer reach the scope of the controller. That is why it is called an 'isolated scope'. It exists for your protection. In large single page apps, you might accidentally change scope variables from the controller which you did not want, if you don't have an isolated scope.
However, we do want to be able to pass variables from the controller to the directive, right? So there is the possibility to build in 'border control' for passing variables from controller to directive. In your html, you pass an extra attribute which is called: in-bold. it has a value. This is your 'border control'. The name 'in-bold' gets transformed to camel case (inBold) for use in javascript.
So what it basically means is that the isolated scope of the directive now has a variable called inBold. The value of this variable is passed to the directive from the controller by the attribute "in-bold". This is important that they have the "same" name. For us humans, in-bold is not the same as inBold, but for angular it is. Everything in angular-html connected with a dash (-) gets transformed in javascript to camel case. So for angular in-bold(html) = inBold(javascript). In the directive, you can now access that passed variable as scope.inBold or {{inBold}}.
Then what is the "#" about? well, the "#" tells the directive that we are dealing with a String value, which is only single-bound. That means that if we change the value of inBold in the directive, the changes will not be visible in the controller! This is important. If you would want two way binding, you would need to use the following:
scope:{
inBold:"="
}
I hope that was a bit clear to you...
This is part of working solution to demonstrate how you can make it bold style. Now you can format the rest part of number
angular.module("myApp", [])
.controller('myController', ['$scope', '$log',
function($scope, $log) {
$scope.phone = '+1(210)22158765';
$scope.isBold = false;
$scope.countryCode = null;
}
])
.directive('ngBoldNumber', [
function() {
return {
restrict: 'A',
template: '<span ng-class="{bold: isBold}">{{countryCode}}</span><span>{{phone}}</span>',
link: function($scope, iElement, iAttrs) {
//debugger;
var x = $scope.phone.substring(0, $scope.phone.indexOf('(') + 1);
var y = $scope.phone.substring($scope.phone.indexOf('(') + 1, $scope.phone.indexOf(')') + 1);
if (x && y) {
$scope.countryCode = x + y;
$scope.isBold = true;
}
}
};
}
]);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="script.js"></script>
<style>
.bold {
font-weight: bold;
}
</style>
</head>
<body ng-app="myApp" ng-controller="myController">
<table class="row">
<tr>
<td ng-bold-number>{{phone}}</td>
</tr>
</table>
</body>
</html>

How to render a HTML tag from json value using angularJs

// json is like this
"_unparsedString": "<p>test<\/p>"
// HTML
<div>Preamble : '{{item2._unparsedString}}'</div>
//Output
Preamble : <p>test<\/p>
but how to render that tag and display it using angular ?
//Output should be like this
Preamble : test
Instead of passing string to view directly, you should use sce.trustAsHtml to pre-process the html.
$scope.bindHTML = $sce.trustAsHtml(item2._unparsedString);
Then in your view template, use ng-bind-html to handle html binding.
<div>Preamble : <div ng-bind-html="bindHTML"></div></div>
As you mentioned you have an array of object, it's not that easy to cast them in your controller, you can bind $sce to your $scope then call trustAsHtml in your view
So in your controller
myapp.controller('mainController', function ($scope, $http, $filter, $sce) {
$scope.$sce = $sce;
...
}
Then in your html view
<div>Preamble {{$index+1}} : <span ng-bind-html="$sce.trustAsHtml(item1.Preamble._unparsedString)"></span></div>
Please check this working example: http://jsfiddle.net/Shital_D/b9qtj56p/6/
Download file - angular-sanitize.js and include it in your app.
var app = angular.module('myApp', ["ngSanitize"]);
app.controller('myController', function($scope,$compile) {
$scope.html = '<p>Your html code</p>';
});
<div ng-app="myApp">
<div ng-controller="myController">
<p ng-bind-html="html"></p>
</div>