在 angularjs 中执行来自页面和指令的事件
Executing events from both page and directive in angularjs
我有两个模块,一个用于实际页面,另一个用于构建可重用组件。我的自定义指令中有一个执行操作 A 的按钮。我在另一个模块页面中使用此指令,其中我有操作 B,一旦单击指令按钮就必须执行该指令。
所以它应该做如下的事情:
dir button click -> function A() + function B() in page.
广播在我工作的环境里好像不太正统
我试过这个plnkr。
代码如下所示:
// Code goes here
angular.module('diruser', ['dir'])
.controller('dirusercon', function($scope) {
$scope.clicks = function(ev) {
console.log('click from page');
console.log(ev);
};
});
angular.module('dir', [])
.controller('dircon', function($scope) {
$scope.dirclick = function(ev) {
console.log('click from dir');
}
})
.directive('dire', function() {
return {
restrict: 'E',
controller: 'dircon',
scope: {
dirclicked: '&'
},
template: "<button ng-click='dirclick($event)'>OK</button>"
};
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='diruser' ng-controller='dirusercon'>
<dire dirclick='clicks(e)'></dire>
</body>
</html>
请帮忙..
在您的示例中,存在错误:
您在范围内定义了一个名为 dirclicked 的函数,但您将其用作 dirclick。
使用必须是:<dire dirclicked='clicks(e)'></dire>
在您的 dirClick 函数中,您必须在范围内调用 dirclicked:
$scope.dirclick = function(ev){
console.log('click from dir');
$scope.dirclicked({e: ev});
}
我编辑了你的插件:http://plnkr.co/edit/2L7ezlPKcChQfulZZtx0?p=preview
我有两个模块,一个用于实际页面,另一个用于构建可重用组件。我的自定义指令中有一个执行操作 A 的按钮。我在另一个模块页面中使用此指令,其中我有操作 B,一旦单击指令按钮就必须执行该指令。
所以它应该做如下的事情:
dir button click -> function A() + function B() in page.
广播在我工作的环境里好像不太正统
我试过这个plnkr。
代码如下所示:
// Code goes here
angular.module('diruser', ['dir'])
.controller('dirusercon', function($scope) {
$scope.clicks = function(ev) {
console.log('click from page');
console.log(ev);
};
});
angular.module('dir', [])
.controller('dircon', function($scope) {
$scope.dirclick = function(ev) {
console.log('click from dir');
}
})
.directive('dire', function() {
return {
restrict: 'E',
controller: 'dircon',
scope: {
dirclicked: '&'
},
template: "<button ng-click='dirclick($event)'>OK</button>"
};
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='diruser' ng-controller='dirusercon'>
<dire dirclick='clicks(e)'></dire>
</body>
</html>
请帮忙..
在您的示例中,存在错误:
您在范围内定义了一个名为 dirclicked 的函数,但您将其用作 dirclick。
使用必须是:<dire dirclicked='clicks(e)'></dire>
在您的 dirClick 函数中,您必须在范围内调用 dirclicked:
$scope.dirclick = function(ev){
console.log('click from dir');
$scope.dirclicked({e: ev});
}
我编辑了你的插件:http://plnkr.co/edit/2L7ezlPKcChQfulZZtx0?p=preview