天天看点

angular指令实例及总结

html代码
<div ng-app="DnApp" ng-controller="SeasonDetailController">
<seamonthdetail seamon="seasonMonth" getseadatas="getSeasonDetailData(month)"></seamonthdetail>
</div>
           
controller代码
var DnApp=angular.module("DnApp",[]);
DnApp.controller('SeasonDetailController',function($scope){
    $scope.seasonMonth=new Date().getMonth()+;
    $scope.getSeasonDetailData=function(month){
        console.log(month);
    }  
})
           
directive代码
DnApp.directive('seamonthdetail',function(){
    return {
        restrict:"EA",
        replace:true,
        transclude:true,
        templateUrl:"/src/tpls/season/monthdetail.html",
        scope:{
            seamon:"=",
            /*使用本地别名
            seasonmonths:"=seamon"
            */
            getseadatas:"&"
        },
        link:function(scope,element,attrs){
            scope.isCurrent=function(name,value){
                if(name==value){
                    return true;
                }else{
                    return false;
                }
            }
            scope.getseasondatas=function(month){
                scope.seamon=month;
                /*调用别名,双向绑定失效
                    scope.seasonmonths=month
                */
/*一定记着,如果函数存在形参,那调用时,一定用对象的形式传递实参*/
                scope.getseadatas({month:month});
            }

        }

    }
})
           
seasondetail.html代码
<div class="flexBox">

    <span ng-class="{true:'active'}[isCurrent(seamon,x.month)]" ng-click="getseasondatas(2)" >
        <i>{{2}}月</i>
    </span>
</div>


/*为了突出函数调用的注意传参的情况,再举个例子。注意这里的实参传递形式*/
<div class="flexBox">

    <span ng-class="{true:'active'}[isCurrent(seamon,x.month)]" ng-click="getseadatas({month:2})" >
        <i>{{2}}月</i>
    </span>
</div>