Ng bind html angularjs

angular ng-bind-html and directive within it

@Chandermani not exactly using directive inside ng-bind-html-unsafe but using filter. But it will do, I just created a filter and passed to the directive. Thanks!

the above solutions don’t handle multiple changes of the value a better solution stackoverflow.com/a/25516311/3343425

6 Answers 6

I was also facing this problem and after hours searching the internet I read @Chandermani’s comment, which proved to be the solution. You need to call a ‘compile’ directive with this pattern:

HTML:

JS:

.directive('compile', ['$compile', function ($compile) < return function(scope, element, attrs) < scope.$watch( function(scope) < // watch the 'compile' expression for changes return scope.$eval(attrs.compile); >, function(value) < // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); >); >; >]) 

In line #2, ie. function(scope, element, attrs) , where did you get from those three arguments, scope, element and attrs?

Читайте также:  Python разработчик где учиться

@spaffy — they’re part of Angular framework’s signature for the link property. They’ll be passed automatically each time when link is called by the Angular framework. They’ll always be available.

Well done. You saved me those same hours of searching. I’m pulling content from SharePoint view REST API, which itself contains Angular markup such as ng-repeat. Your directive made it all work. Thanks!

Thanks for your directive it fixed the problems I was having. Now the angular code gets compiled but too many times. A ng-repeat with 3 object turns into the same values just 3x each. Whats going wrong here?

If you have been using $sce.trustAsHtml from another function to create the HTML that will be «compiled» with this directive, you should remove it. Thanks to @apoplexy

Thanks for the great answer vkammerer. One optimization I would recommend is un-watching after the compilation runs once. The $eval within the watch expression could have performance implications.

 angular.module('vkApp') .directive('compile', ['$compile', function ($compile) < return function(scope, element, attrs) < var ensureCompileRunsOnce = scope.$watch( function(scope) < // watch the 'compile' expression for changes return scope.$eval(attrs.compile); >, function(value) < // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); // Use un-watch feature to ensure compilation happens only once. ensureCompileRunsOnce(); >); >; >]); 

Warning: The fiddle for this answer works, but the .directive() code in the code posted in the answer does not.

this one worked for me. the chosen answer would trigger «Error: $rootScope:infdig Infinite $digest Loop»

You shouldn’t need the explict $eval — you can just use attrs.compile directly in place of the watched anonymous function. If you just provide a string expression, angular will call $eval on it anyway.

.directive('bindHtmlCompile', ['$compile', function ($compile) < return < restrict: 'A', link: function (scope, element, attrs) < scope.$watch(function () < return scope.$eval(attrs.bindHtmlCompile); >, function (value) < // Incase value is a TrustedValueHolderType, sometimes it // needs to be explicitly called into a string in order to // get the HTML string. element.html(value && value.toString()); // If scope is provided use it, otherwise use parent scope var compileScope = scope; if (attrs.bindHtmlScope) < compileScope = scope.$eval(attrs.bindHtmlScope); >$compile(element.contents())(compileScope); >); > >; >]); 

Be careful, if you pass something like this: «$scope.loadContent = function() < return $sce.trustAsHtml(require('html/main-content.html')); >;» to it you can get infinite digest loop. Without the trustAsHtml it works.

I tried this option. Works like a charm! I also use $sce.trustAsHtml before passing it to the directive. Thanks!

Unfortunately I don’t have enough reputation to comment.

I could not get this to work for ages. I modified my ng-bind-html code to use this custom directive, but I failed to remove the $scope.html = $sce.trustAsHtml($scope.html) that was required for ng-bind-html to work. As soon as I removed this, the compile function started to work.

For anyone dealing with content that has already been run through $sce.trustAsHtml here is what I had to do differently

function(scope, element, attrs) < var ensureCompileRunsOnce = scope.$watch(function(scope) < return $sce.parseAsHtml(attrs.compile)(scope); >, function(value) < // when the parsed expression changes assign it into the current DOM element.html(value); // compile the new DOM and link it to the current scope. $compile(element.contents())(scope); // Use un-watch feature to ensure compilation happens only once. ensureCompileRunsOnce(); >); > 

This is only the link portion of the directive as I’m using a different layout. You will need to inject the $sce service as well as $compile .

Источник

Ng bind html angularjs

Привязка данных раскрывается через ряд директив:

  • ng-bind : осуществляет привязку к свойству innerText html-элемента
  • ng-bind-html : осуществляет привязку к свойству innerHTML html-элемента
  • ng-bind-template : аналогична ng-bind за тем исключением, что позволяет установить привязку сразу к нескольким выражениям
  • ng-model : создает двустороннюю привязку
  • ng-non-bindable : определяет участок html-кода, в котором привязка не будет использоваться

Рассмотрим директивы на примере того же контроллера phonesController :

var myApp=angular.module('myApp', []); myApp.controller('phoneController', function($scope) < $scope.phones = [< name: 'Nokia Lumia 630', year: 2014, price: 200, company: < name: 'Nokia', country: 'Финляндия' >>, < name: 'Samsung Galaxy S 4', year: 2014, price: 400, company: < name: 'Samsung', country: 'Республика Корея' >>, < name: 'Mi 5', year: 2015, price: 300, company: < name: 'Xiaomi', country: 'Китай' >>] >);

ng-bind

Директива ng-bind используется для создания односторонней привязки одного элемента html к какому-нибудь выражению. И если данное выражение изменится, то вместе с ним обновится и содержимое связанного элемента html. Например, в прошлом разделе мы использовали массив моделей phone. Свяжем элемент с одним из таких объектов:

 

Количество элементов:

Первый элемент:

Здесь идет привязка к длине массива phones и к первому его элементу. Если мы добавим в массив новый элемент или изменим название первого элемента, то соответственно изменится и текст в привязанных элементах span .

ng-model

Директива ng-model позволяет выполнять двустороннюю привязку как к свойствам объекта, так и к вложенным свойствам:

Директиву ng-model можно использовать для привязки к элементам input , textarea и select :

При изменении текста в поле ввода синхронно будет изменяться и привязанный к phones[0].name элемент p .

ng-bind-template

Директива ng-bind-template позволяет задать шаблон привязки с использованием выражений. Например:

ng-non-bindable

Но бывает, что нам надо, чтобы AngularJS не обрабатывал какие-то выражения и не использовал привязку. В этом случае мы можем применить директиву ng-non-bindable :

Если в первом случае AngularJS обработает выражение и выведет на страницу его результат, то во втором случае выражение будет выведено как есть.

ng-bind-html

Директива ng-bind-html позволяет выводить на страницу html-содержимое со всеми тегами. При использовании этой директивы необходимо помнить, результатом вывода может быть потенциально небезопасный код, например, содержащий javascript, поэтому данный аспект надо учитывать.

Чтобы осуществить привязку к коду html, надо подключить дополнительный файл. В архиве библиотеки, который можно найти на официальном сайте, имеется файл angular-sanitize.js , а также его минимизированный аналог. Положим этот файл в одну папку с главной библиотекой angularjs и изменим код страницы следующим образом:

         

директива ng-bind-html

Чтобы задествовать модуль angular-sanitize, надо при создании модуля установить зависимость от angular-sanitize: var myApp = angular.module(‘myApp’, [«ngSanitize»]); . После этого мы сможем изменять код в текстовом поле, в том числе вносить код html, и все изменения автоматически будут применяться к веб-странице.

Источник

AngularJS ng-bind Directive

Bind the innerHTML of the

element to the variable myText:

Definition and Usage

The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression.

If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.

Syntax

Supported by all HTML elements.

Parameter Values

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Ng bind html angularjs

  • AngularJS | Directives
  • AngularJS ng-app Directive
  • AngularJS ng-bind Directive
  • AngularJS ng-bind-html Directive
  • AngularJS ng-bind-template Directive
  • AngularJS ng-blur Directive
  • AngularJS ng-change Directive
  • AngularJS ng-checked Directive
  • AngularJS ng-class Directive
  • AngularJS ng-class-even Directive
  • AngularJS ng-class-odd Directive
  • AngularJS ng-click Directive
  • AngularJS ng-cloak Directive
  • AngularJS ng-controller Directive
  • AngularJS Directives Complete Reference

AngularJS Filters

AngularJS Converting Functions

AngularJS Comparing Functions

  • AngularJS angular.isArray() Function
  • AngularJS angular.isDate() Function
  • AngularJS angular.isDefined() Function
  • AngularJS angular.isElement() Function
  • AngularJS angular.isFunction() Function
  • AngularJS angular.isNumber() Function
  • AngularJS angular.isObject() Function
  • AngularJS | angular.isString() Function
  • AngularJS angular.isUndefined() Function
  • AngularJS angular.equals() Function
  • AngularJS angular.toJson() Function

AngularJS Questions

AngularJS Basics

  • AngularJS Tutorial
  • Introduction to AngularJS
  • Angular CLI | Angular Project Setup
  • AngularJS Expressions
  • AngularJS Modules
  • AngularJS ng-model Directive
  • AngularJS Data Binding
  • AngularJS Controllers
  • AngularJS | Scope
  • AngularJS Services
  • AngularJS | AJAX – $http
  • AngularJS | Tables
  • AngularJS Select Boxes
  • AngularJS | SQL
  • AngularJS HTML DOM
  • AngularJS Events
  • AngularJS | Forms
  • AngularJS Form Validation
  • AngularJS | API
  • AngularJS and W3.CSS
  • AngularJS Includes
  • AngularJS Animations
  • AngularJS Routing
  • AngularJS | Application
  • AngularJS | Directives
  • AngularJS ng-app Directive
  • AngularJS ng-bind Directive
  • AngularJS ng-bind-html Directive
  • AngularJS ng-bind-template Directive
  • AngularJS ng-blur Directive
  • AngularJS ng-change Directive
  • AngularJS ng-checked Directive
  • AngularJS ng-class Directive
  • AngularJS ng-class-even Directive
  • AngularJS ng-class-odd Directive
  • AngularJS ng-click Directive
  • AngularJS ng-cloak Directive
  • AngularJS ng-controller Directive
  • AngularJS Directives Complete Reference

AngularJS Filters

AngularJS Converting Functions

AngularJS Comparing Functions

  • AngularJS angular.isArray() Function
  • AngularJS angular.isDate() Function
  • AngularJS angular.isDefined() Function
  • AngularJS angular.isElement() Function
  • AngularJS angular.isFunction() Function
  • AngularJS angular.isNumber() Function
  • AngularJS angular.isObject() Function
  • AngularJS | angular.isString() Function
  • AngularJS angular.isUndefined() Function
  • AngularJS angular.equals() Function
  • AngularJS angular.toJson() Function

AngularJS Questions

Источник

Ng bind html angularjs

  • AngularJS | Directives
  • AngularJS ng-app Directive
  • AngularJS ng-bind Directive
  • AngularJS ng-bind-html Directive
  • AngularJS ng-bind-template Directive
  • AngularJS ng-blur Directive
  • AngularJS ng-change Directive
  • AngularJS ng-checked Directive
  • AngularJS ng-class Directive
  • AngularJS ng-class-even Directive
  • AngularJS ng-class-odd Directive
  • AngularJS ng-click Directive
  • AngularJS ng-cloak Directive
  • AngularJS ng-controller Directive
  • AngularJS Directives Complete Reference

AngularJS Filters

AngularJS Converting Functions

AngularJS Comparing Functions

  • AngularJS angular.isArray() Function
  • AngularJS angular.isDate() Function
  • AngularJS angular.isDefined() Function
  • AngularJS angular.isElement() Function
  • AngularJS angular.isFunction() Function
  • AngularJS angular.isNumber() Function
  • AngularJS angular.isObject() Function
  • AngularJS | angular.isString() Function
  • AngularJS angular.isUndefined() Function
  • AngularJS angular.equals() Function
  • AngularJS angular.toJson() Function

AngularJS Questions

AngularJS Basics

  • AngularJS Tutorial
  • Introduction to AngularJS
  • Angular CLI | Angular Project Setup
  • AngularJS Expressions
  • AngularJS Modules
  • AngularJS ng-model Directive
  • AngularJS Data Binding
  • AngularJS Controllers
  • AngularJS | Scope
  • AngularJS Services
  • AngularJS | AJAX – $http
  • AngularJS | Tables
  • AngularJS Select Boxes
  • AngularJS | SQL
  • AngularJS HTML DOM
  • AngularJS Events
  • AngularJS | Forms
  • AngularJS Form Validation
  • AngularJS | API
  • AngularJS and W3.CSS
  • AngularJS Includes
  • AngularJS Animations
  • AngularJS Routing
  • AngularJS | Application
  • AngularJS | Directives
  • AngularJS ng-app Directive
  • AngularJS ng-bind Directive
  • AngularJS ng-bind-html Directive
  • AngularJS ng-bind-template Directive
  • AngularJS ng-blur Directive
  • AngularJS ng-change Directive
  • AngularJS ng-checked Directive
  • AngularJS ng-class Directive
  • AngularJS ng-class-even Directive
  • AngularJS ng-class-odd Directive
  • AngularJS ng-click Directive
  • AngularJS ng-cloak Directive
  • AngularJS ng-controller Directive
  • AngularJS Directives Complete Reference

AngularJS Filters

AngularJS Converting Functions

AngularJS Comparing Functions

  • AngularJS angular.isArray() Function
  • AngularJS angular.isDate() Function
  • AngularJS angular.isDefined() Function
  • AngularJS angular.isElement() Function
  • AngularJS angular.isFunction() Function
  • AngularJS angular.isNumber() Function
  • AngularJS angular.isObject() Function
  • AngularJS | angular.isString() Function
  • AngularJS angular.isUndefined() Function
  • AngularJS angular.equals() Function
  • AngularJS angular.toJson() Function

AngularJS Questions

Источник

Оцените статью