简体   繁体   English

通过append方法调用角度指令

[英]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, 我试图用我在控制器中附加的html文本调用angular指令,

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. 如果我在html中加载star指令,则可以正常工作,但是通过这种方法,不会加载任何内容。 I've looked into $compile but it did not fix the issue, but I may have applied it incorrectly. 我研究了$ compile,但是它不能解决问题,但是我可能未正确应用它。

I would avoid adding manually the directive into the html, I would recommend let angular being in charge of adding html content. 我会避免将指令自动添加到html中,我建议让angular负责添加html内容。

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) 现在有些情况下,您将需要附加html内容(如在模式中),在这种情况下,您需要先使用$ compile服务来编译html,然后再附加html,然后再合并作用域(它可以是新的,也可以是相同的一)

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 以下是本·莱什(Ben Lesh)的一个很棒的示例,该示例如何执行该操作: http : //www.benlesh.com/2013/08/angular-compile-how-it-works-how-to-use.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM