gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:20:12 25 4
gpt4 key购买 nike

我正在尝试使用我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com