msforest / notebook

好记性不如烂笔头,记录知识的点点滴滴。
https://github.com/msforest/notebook/wiki
0 stars 0 forks source link

directive在不同controller使用 #5

Open msforest opened 7 years ago

msforest commented 7 years ago

在angular的路上,一步步摸索,在工作中慢慢尝试。 自定义指令貌似很简单,不过肯定还有不为我知的地方,先从简单入手,自定义一个load指令:

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

app.directive('load', function(){
    return {
        restrict:'E',
        link:function(scope,element,attr){
            element.bind('mouseenter', function(){
                scope.$apply(attr.howtoload);  //需小写,对应属性howToLoad
            });
        }
    }
})

howtoload一定要在apply方法里,否则angular是无法对其进行监听。这里使用到link函数,涉及一点angular的生命周期,要想使用指令对事件进行操作,需要在指令编译后,然后用link函数创建可以操作DOM的事件。下面使用指令在控制器进行声明:

<div ng-controller="loadCtrl1">
    <load howToLoad="load1()">loading...</load>
</div>
<div ng-controller="loadCtrl2">
    <load howToLoad="load2()">loading...</load>
</div>

定义控制器方法

app.controller('loadCtrl1',['$scope', function($scope){
    $scope.load1 = function(){
        console.log('loading...');
    }
}])

app.controller('loadCtrl2',['$scope', function($scope){
    $scope.load2 = function(){
        console.log('loading...222');
    }
}])