html 代码片段
<body>
<div ng-controller="boxController">
<box>滑动加载</box>
</div>
</body>
controller 代码片段
boxApp.controller('boxController', ['$scope',function($scope) {
$scope.loadData = function(){
console.log("数据加载中。。。。");
};
}]);
directive 代码片段
boxApp.directive("box", ["$timeout",function($timeout) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.bind('mouseenter', function() {
// scope.loadData();
scope.$apply("loadData()");
});
};
}]);
directive在不同controller中使用,假如有 boxController2,如何根据不同的controller调用不同的方法,需要给directive定义属性
此页面定义了howToLoad属性
html代码片段
<div ng-controller="bomController">
<bom howToLoad="loadData()"></bom>
</div>
<div ng-controller="bomController2">
<bom howToLoad="loadData2()"></bom>
</div>
controller 代码片段
boxApp.controller('boxController', ['$scope',function($scope) {
$scope.loadData = function(){
console.log("数据加载中。。。。");
};
}]);
boxApp.controller('boxController2', ['$scope',function($scope) {
$scope.loadData2 = function(){
console.log("数据加载中2222。。。。");
};
}]);
directive 代码片段
boxApp.directive("box", ["$timeout",function($timeout) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.bind('mouseenter', function() {
// scope.loadData();
scope.$apply(attrs.howtoload);
});
};
}]);
directive 代码需要注意 attrs.howtoload 要全部小写,如果在html中按照驼峰法则howToLoad来写的话,为了避免错误,可以全部采用小写的格式,不要忘记atrrs,不要加括号。
结果
参考 慕课网 Angularjs 实战