Ionic1x实现简单的评论星级组件

最近敲代码,需要个评论星级,因为好多地方都需要评级,干脆直接封装成一个指令,方便了好多,代码很简单,毕竟实现的东西也不多,有问题大家可以一起讨论下,希望能帮到好学的coder。
Ionic2差不多也,毕竟原理就那么回事

/**
 *  评论星级组件
 */

app .directive('star', function () {  
            return {
                restrict: 'EA',
                scope: {
                    num: "=",//是父元素传过来的评论星级数(1,2,3,4,5)之类的
                    readonly: "@"//是否可读,毕竟有的地方只需要读取就可以了
                },
                templateUrl: './js/directives/star.html',            
                link: function(scope, element, attrs) { 
                    scope.stars = [];
                    for (var i = 1; i<=5; i++) {
                        scope.stars.push(i > scope.num);
                      }
                    scope.clickStar = function(index) {
                            if(!scope.readonly) {
                                  scope.num = index;
                             }  
                            scope.stars = [];
                            for (var i = 1; i<=5; i++) {
                                scope.stars.push(i > scope.num);
                              }
                        }
                    }
                }
        })  

html中的内容

<div>
    <span ng-repeat='star in stars track by $index'><i class="assertive" ng-class="{true: 'ion-ios-star-outline ', false: 'ion-ios-star'}[star]"  on-tap="clickStar($index+1)"></i>&nbsp;</span>
</div>

使用起来也很简单

<star num=item.star readonly="true"></star>

这里其实我原本是写在指令中的,但是被字符串拼接给搞烦了,ES6模板字符串就是好,希望能早日用到项目里(流泪- -)。

猜你喜欢

转载自blog.csdn.net/qq_26626113/article/details/78034595