FutuToad
FutuToad

Reputation: 2850

How can I get my directive to access the controllers scope

I have a setup like this:

<controller>
   <directive>

in my controller that has a function that returns an html string. How can I get my directive to render this by accessing the controllers scope?

Or maybe I should just put the controller in the directive?

app.controller('controller', ['$scope', 'DataService', function ($scope, DataService) {

    $scope.parseJson = function () {
      //returns the html
    };

}]);

directive

app.directive('Output', function () {
  return {
    restrict: 'A',
    replace: true,
    template: '<need html from controller>',
    link: function(scope, element, attr) {

        //render
        //scope.parseJson();
    }
  };
});

Upvotes: 0

Views: 100

Answers (3)

CodePrimate
CodePrimate

Reputation: 6666

app.directive('Output', function ($compile) {
      return {
        restrict: 'A',
        link: function(scope, element, attr) {
            var templateString = scope.parseJson();
            var compiledTemplate = $compile(templateString)(scope);
            compiledTemplate.appendTo("TheElementYouWishtoAppendYourDirectiveTo");
        }
      };
    });

Upvotes: 1

Ilan Frumer
Ilan Frumer

Reputation: 32397

You should use the isolated scope: '&' option

app.directive('output', ['$sce', function ($sce) {
  return {
    restrict: 'A',
    replace: true,
    template: "<div ng-bind-html='parsed'></div>",
    scope:{
      output: "&"
    },
    link: function(scope){
      scope.parsed = $sce.trustAsHtml(scope.output());
    }
  };
}]);

Template:

<div output="parseJson()"></div>

Upvotes: 2

bmceldowney
bmceldowney

Reputation: 2305

The directive and the controller should be sharing the scope already. Don't bother using a template for the directive, just get the HTML string in you linking function (you already have the method call in there) and modify the element directly using element.html(). Take a look at the element docs for more info.

Upvotes: 1

Related Questions