【问题标题】:Angular 2 DirectiveAngular 2 指令
【发布时间】:2018-01-17 05:24:05
【问题描述】:

根据 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 中也可以这样做吗?如果是这样,它会怎么做?我找不到任何合适的代码示例或教程。

谢谢 彼得

【问题讨论】:

标签: angularjs angular angular2-directives


【解决方案1】:

好的,我发现自己是一个合适的解决方案:

在组件中我刚刚添加了一个功能

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 2019-11-30
    • 2017-06-11
    • 2017-06-27
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多