我们先看一个简单的代码:
<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div ng-controller="MyCtrl">
<loader>滑动加载</loader>
</div>
</body>
<script src="framework/angular-1.3.0.14/angular.js"></script>
</html>
<script>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function ($scope) {
$scope.loadData = function () {
console.log("加载数据中...");
}
}]);
myModule.directive("loader", function () {
return {
restrict: "AE",
link: function (scope, element, attrs) {
element.bind('mouseenter', function (event) {
scope.loadData();
});
}
}
});
</script>
通过link
监听鼠标滑动时间,调用控制器loadData
方法。
指令的复用
上面的实现方式,只能加载调用指定的控制器,无法进行复用,我们通过属性
,来实现调用不同的控制器,来加载不同的数据:
<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
<script src="https://www.orchome.com/user/js/angular-1.5.8.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<loader howToLoad="loadData()">滑动加载</loader>
</div>
<div ng-controller="MyCtrl2">
<loader howToLoad="loadData2()">滑动加载</loader>
</div>
</body>
</html>
<script>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function ($scope) {
$scope.loadData = function () {
console.log("加载数据中...");
}
}]);
myModule.controller('MyCtrl2', ['$scope', function ($scope) {
$scope.loadData2 = function () {
console.log("加载数据中...22222");
}
}]);
myModule.directive("loader", function () {
return {
restrict: "AE",
link: function (scope, element, attrs) {
element.bind('mouseenter', function (event) {
// scope.loadData();
// scope.$apply("loadData()");
// 注意这里的坑,howToLoad会被转换成小写的howtoload
scope.$apply(attrs.howtoload);
});
}
}
});
</script>