R
R
Roman Yamchuk2017-06-20 11:40:02
Angular
Roman Yamchuk, 2017-06-20 11:40:02

How to compile a directive obtained from json?

Loading html from json.
View controller:

$http.get('/content/' + page + 'index.json')
  .then(function successCallback(response) {
    var html = response.data.html;
      $scope.data = {
        name: response.data.name,
        class: response.data.type ? 'is-' + response.data.type : '',
        content: $sce.trustAsHtml(html)
      };
  }, function errorCallback(response) {
      alert('404');
      $location.path('/' + Lang.get() + '/');
});

Directive
angular.module('scrollbar', [])
.directive('ngScrollbar', ['$compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      console.log('compiled')
    }
  }
}]);

sample json
{
  "name": "Климат",
  "html": "<div data-ng-scrollbar><p>Этот период отличает наибольшее число осадков, наличие штормов и северного ветра. Теплая погода наступает на полуострове внезапно, но именно в марте и апреле разница между дневной и ночной температуры ощущается особенно сильно.</p></div>"
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
ozknemoy, 2017-06-20
@tomgif

the first part is already done($sce.trustAsHtml(html)). left in the view directive ng-bind-html="data.content" but Angular chips do not work from this method. therefore, we take not the scrollbar directive, but the component, we pass the html content from the server through the binding and compile this html in the $onChanges method:

this.$onChanges = (changes)=> {
if(changes.nameOfBinding && changes.nameOfBinding.currentValue ) {
var element = $compile(changes.nameOfBinding.currentValue)($scope);
 $element.append(element )
}
  
}

N
Nicholas, 2017-06-20
@healqq

You can use ng-bind-html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question