Binding ng-directives

techies
Kilo Expert

Hi All,

I am binding a number box to a html page and require the number box to use some ng-direvtives.

I am doing it as follows.

var bind = $sce.trustAsHtml("<input step=\"0.01\" ng-model=\"model\" ng-change=\"c.uiActionFunction('action')\" type=\"number\"   "id=\"number\"/>")

<div ng-bind-html="bind"></div>

The number box works fine and I can retrieve the value however the ng directives don't work. After searching online its because you have to compile the variable to be able to use the directives but I don't see how this can be done in service now.

Does anyone have any suggestions on how to do this?

Thanks for any help.

6 REPLIES 6

Shishir Srivast
Mega Sage

Hi Roni,



I am not sure if ng-bind should be in div tag, Please find the below link for further help. Thank you!



AngularJS


AngularJS


Angular ng-bind-html Directive



Thank you!


Karthik Reddy T
Kilo Sage

Hello Roni,



Refer the below links may helpful to you.



Angular ng-bind Directive



Angular Expressions



AngularJS



javascript - AngularJS : Why ng-bind is better than {{}} in angular? - Stack Overflow


Karthik Reddy T.
ServiceNow Commnunity MVP -2018 class.

Hi,


The problem is to be able to bing ng-directives. The html itself works.


iurii_raboshuk
Giga Contributor

Hi Roni,



You are right, ng-bind-html doesn't recognize the bound HTML as a template hence it never gets compiled. From your question I understand that you want to implement a dynamic Angular template support. This could be achieved in several ways.


1. Use ng-if, ng-show/ng-hide, ng-switch/ng-switch-when etc. Those directives allow you to make your template dynamic if you have a predefined set of use cases.


2. Use $compile service to make Angular compile some DOM element(s) and bind them to specific scope. This works for any custom template. Though it is possible to use this service in the controller, I would highly recommend to avoid doing so. This approach implies direct DOM manipulation which is safe to be done only in the directive's link function.



Which one of the above is your case?



Some API links:


$compile: https://docs.angularjs.org/api/ng/service/$compile


ng-if: https://docs.angularjs.org/api/ng/directive/ngIf  


ng-show: https://docs.angularjs.org/api/ng/directive/ngShow


ng-hide: https://docs.angularjs.org/api/ng/directive/ngHide



Iurii Raboshuk