html 代码片段
<body> <div ng-controller="boxController"> <box>滑动加载</box> </div> </body>
boxApp.controller('boxController', ['$scope',function($scope) { $scope.loadData = function(){ console.log("数据加载中。。。。"); }; }]);
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>
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); }); }; }]);
结果
参考 慕课网 Angularjs 实战