1

I'm trying to call an angular directive with html text I am appending in my controller like so,

var loadReviews=function(){
var theDiv=$("#rlist")
   for(var i=0; i<vm.reviewlistByUpvote.length; i++){
       var review=vm.reviewlistByUpvote[i];
       var html='<a star-directive ng-model="review.overall" data-size="xs" data-disabled="true"> </a>';
       theDiv.append(html)
 };
};

And my directive looks as follows,

angular.module('App')
.directive('starDirective', function() {
return {
  restrict: 'A',
  // templateUrl: 'views/star.html',
  link: function(scope, element, attrs, ngModel) {
        $(element).rating(scope.$eval(attrs.starRating));

              // get value from ng-model
        ngModel.$render = function() {
            $(element).rating('update', ngModel.$viewValue || '');
        }



          $(element).on('rating.change', function(event, value, caption) {
            ngModel.$setViewValue(value);
        });
         }


   };
 });

However, the directive won't compile. If I load the star directive within my html, it works fine, but through this approach, nothing gets loaded. I've looked into $compile but it did not fix the issue, but I may have applied it incorrectly.

4
  • Not sure why you commented out templateUrl in directive. That would be a far more proper way to make this work and get rid of your jQuery dom manipulation. Also not sure why you are using ng-model on <a> tags. There is no view value to set, that is for form controls Commented Feb 16, 2016 at 18:31
  • Create a simple demo with what you have that includes the plugin resources Commented Feb 16, 2016 at 18:32
  • I tried doing templateUrl first, but then I wasn't sure how to pass in a list of reviews, and have it generate content for each review. Is there a way to pass in parameters into the the template url? Commented Feb 16, 2016 at 18:57
  • no...you pass in data to directive through attributes on tag the directive is assigned to Commented Feb 16, 2016 at 18:58

1 Answer 1

1

I would avoid adding manually the directive into the html, I would recommend let angular being in charge of adding html content.

Now there are cases where you will need to append html content (like in modals), in this case you need to compile the html using $compile service before appending the html and then assing a scope (it can be a new one or the same one)

Here is a cool example from Ben Lesh of how to do that: http://www.benlesh.com/2013/08/angular-compile-how-it-works-how-to-use.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.