Angular 2 条指令
Angular 2 Directive
根据 Angular 2 条指令,我有一个问题。我想用 Angular 2 重新创建我的 Angular 1 应用程序,但我被指令卡住了。
Angular 1 中的那个看起来像这样:
app.directive('starRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars">' +
'<span class="glyphicon" ng-class="star.class" aria-hidden="true">' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '='
},
link: function (scope, elem, attrs) {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
if(i < scope.ratingValue){
scope.stars.push({
class: "glyphicon-star"
});
} else {
scope.stars.push({
class: "glyphicon-star gray"
});
}
}
}
}
});
我在 html 文件中这样调用它:
<div star-rating rating-value="movie.rating" max="5" ></div>
这只是一个带有名称和评级的简单电影列表。通过该指令,我只想创建 5 颗星,并且根据评分,应填充星数。
在 Angular 2 中也可以这样做吗?如果是这样,它将如何完成?我找不到任何合适的代码示例或教程。
谢谢
彼得
好的,我找到了一个合适的解决方案:
在组件中我刚刚添加了一个函数
getClass(index, rating) {
if (index < rating) {
return 'glyphicon-star';
} else {
return 'glyphicon-star-empty gray';
}
}
在我的 HTML 中,我这样称呼它:
<div class="col-lg-3">
<ul class="rating">
<li *ngFor="let n of [0,1,2,3,4]; let i = index">
<span class="glyphicon" [ngClass]="getClass(i, rating)"></span>
</li>
</ul>
</div>
根据 Angular 2 条指令,我有一个问题。我想用 Angular 2 重新创建我的 Angular 1 应用程序,但我被指令卡住了。 Angular 1 中的那个看起来像这样:
app.directive('starRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars">' +
'<span class="glyphicon" ng-class="star.class" aria-hidden="true">' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '='
},
link: function (scope, elem, attrs) {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
if(i < scope.ratingValue){
scope.stars.push({
class: "glyphicon-star"
});
} else {
scope.stars.push({
class: "glyphicon-star gray"
});
}
}
}
}
});
我在 html 文件中这样调用它:
<div star-rating rating-value="movie.rating" max="5" ></div>
这只是一个带有名称和评级的简单电影列表。通过该指令,我只想创建 5 颗星,并且根据评分,应填充星数。
在 Angular 2 中也可以这样做吗?如果是这样,它将如何完成?我找不到任何合适的代码示例或教程。
谢谢 彼得
好的,我找到了一个合适的解决方案:
在组件中我刚刚添加了一个函数
getClass(index, rating) {
if (index < rating) {
return 'glyphicon-star';
} else {
return 'glyphicon-star-empty gray';
}
}
在我的 HTML 中,我这样称呼它:
<div class="col-lg-3">
<ul class="rating">
<li *ngFor="let n of [0,1,2,3,4]; let i = index">
<span class="glyphicon" [ngClass]="getClass(i, rating)"></span>
</li>
</ul>
</div>