Vohn
Vohn

Reputation: 11

Calling an angular directive via append method

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.

Upvotes: 1

Views: 267

Answers (1)

jfplataroti
jfplataroti

Reputation: 661

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

Upvotes: 1

Related Questions