js:
const myapp = angular.module('myapp',[]);
myapp.controller('ctrl1',['$scope',function ($scope) {
$scope.loadData= function () {
console.log(" 执行了加载数据的函数1");
};
}]);
myapp.controller('ctrl2',['$scope',function ($scope) {
$scope.loadData2= function () {
console.log(" 执行了加载数据的函数222");
};
}]);
myapp.directive('hello',function () {
return {
restrict:'AE',
template:"<div>load hello data<div>",
replace:true,
link:function (scope,element,attr) { // scope是link函数接收来的,上面传过来的$scope
element.bind('mouseenter',function () {
// scope.loadData(); // 调用上面传过来的$scope的方法,也可以用apply来调用
// scope.$apply("loadData()"); // 用apply注意是传入字符串,并且字符串是完整的调用形式,即带括号()
scope.$apply(attr.howtoload); // 这里的howtoload是属性名,就是对应的函数名的一个变量名,别名
// 特别注意这里的属性用的是小写,这是个坑,就是在directive中自定义的属性,在js中要小写
// 不然,不报错,但是找不到,执行不到!
})
}
}
});
html:
<div hello ng-controller="ctrl1" howToLoad="loadData()"></div>
<hello ng-controller="ctrl2" howToLoad="loadData2()"></hello>