通过追加方法调用角度指令

Calling an angular directive via append method

本文关键字:指令 调用 方法 追加      更新时间:2023-09-26

我正在尝试调用一个带有 html 文本的角度指令,我像这样附加到我的控制器中,

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)
 };
};

我的指令如下,

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);
        });
         }

   };
 });

但是,该指令不会编译。如果我在我的 html 中加载 star 指令,它工作正常,但通过这种方法,什么都没有加载。我已经调查了$compile但它没有解决问题,但我可能应用不正确。

我会避免手动将指令添加到 html 中,我建议让 angular 负责添加 html 内容。

现在在某些情况下,您需要附加 html 内容(如在模态中(,在这种情况下,您需要在附加 html 然后构建范围之前使用$compile服务编译 html(它可以是一个新的或相同的(

以下是Ben Lesh如何做到这一点的一个很酷的例子:http://www.benlesh.com/2013/08/angular-compile-how-it-works-how-to-use.html