实际上我需要的是放置一个可以访问$ scope的可重用函数。
以下是我尝试做的简化示例的尝试: Plnkr
我仍然掌握指令。
var app = angular.module('plunker', []);
app.directive('dir1', function() {
return {
restrict: 'AE',
link: function(scope, element, attrs) {
element.click(function() {
scope.message = "Hey Now";
scope.doSomething();
});
}
};
});
app.directive('dir2', function() {
return {
restrict: 'AE',
link: function(scope, elem, attr) {
scope.doSomething = function() {
alert($scope.message);
}
}
};
});
和:
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<dir1>click me</dir1>
</body>
</html>
答案 0 :(得分:1)
您可以使用require
指令参数与另一个指令进行通信。这是一个例子:
var app = angular.module('plunker', []);
app.directive('dir1', function(){
return {
restrict: 'AE',
require:'dir2',
link: function(scope, element, attrs, dir2) {
element.bind('click', function() {
dir2.message = "Hey Now";
alert(JSON.stringify(dir2))
dir2.doSomething();
});
}
};
});
app.directive('dir2', function(){
return {
restrict: 'AE',
controller : function ($scope) {
this.doSomething = function(){
alert(this.message);
}
}
};
});