javascript - 通过追加方法调用 Angular Directive(指令)

标签 javascript jquery angularjs angularjs-directive directive

我正在尝试使用我在 Controller 中附加的 html 文本调用 Angular Directive(指令),如下所示,

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

关于javascript - 通过追加方法调用 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35440219/

相关文章:

javascript - 每次单击扩展按钮时无法发出响应

html - AngularJS - 关于 ngBindHtml 的文本区域文本

javascript - If 条件推送包含/匹配字符串的值

javascript - 在 IFRAME 沙箱模式下 Google App 脚本中获取错误的 url

javascript - 每次提交注册表单时,如何将变量从数据库传递到 url

javascript - 使用 jquery 更改 <ul> 内某些 <li> 的 CSS

javascript - 我如何知道在 JavaScript 中点击了页面上的哪个 <li> 标签?

jquery - 数组输入中的每个问题

angularjs - 如何向每个 Angular.js $http 请求添加添加请求参数(例如启动 xdebug session )

javascript - 我应该从 Protractor 中 Element 的 getText() promise 分配变量还是返回变量