码迷,mamicode.com
首页 > 其他好文 > 详细

angular directive指令的复用

时间:2016-04-24 15:37:35      阅读:483      评论:0      收藏:0      [点我收藏+]

标签:

“指令之之所以要定义成指令就是为了复用!”

指令一定是可以用在不同的controller里面的,为了在不同的controller去使用它,我们一定要给指定的配置项一个指令。这样才能跟外面的控制器进行交互。

举例如下:

html:

    <div ng-controller="MyCtrl">
        <loader howToLoad="loadData()">滑动加载</loader>
    </div>
    <div ng-controller="MyCtrl2">
        <loader howToLoad="loadData2()">滑动加载2</loader>
    </div>

js:

var app = angular.module(MyModule,[]);

app.controller(MyCtrl, [$scope,function($scope){
    $scope.loadData = function(){
        console.log("加载数据中...");
    }
}]);

app.controller(MyCtrl2, [$scope,function($scope){
    $scope.loadData2 = function(){
        console.log("加载数据中...2222");
    }
}]);

app.directive("loader",function(){
    return{
        restrict: "AE",
        link:function(scope,element,attrs){      /*link函数有4个参数,最后一个父控制器,此处用了3个*/
            element.bind(mouseenter,function(){
                // scope.$apply("loadData()");
                // 注意这里的坑,howtoload会被转换成小写的howtoload
                scope.$apply(attrs.howtoload);
            });
        }
    }
});

 

angular directive指令的复用

标签:

原文地址:http://www.cnblogs.com/91allan/p/5427064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!