实际上,我所需要的只是放置一个可以访问$scope的可重用函数。
下面是我试图做的一个简化的例子:普朗克
我还在掌握指令的窍门。
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>发布于 2014-08-16 02:21:14
您可以使用指令的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);
}
}
};
});https://stackoverflow.com/questions/25335189
复制相似问题