嗨,我正在处理这个“可确认”按钮指令,
将触发指令“可确认”的 html 代码
<span confirmable ng-click='users.splice($index,1)'></span>
指令:(咖啡稿)
angular.module('buttons',[])
.directive 'confirmable', () ->
template: """
<button class='btn btn-mini btn-danger'>
Destroy
</button>
"""
replace: yes
所以我想看到用这个指令生成的最终结果是
<button class='btn btn-mini btn-danger' ng-click='users.splice($index,1)'>
Destroy
</button>
到目前为止,我让它与指令中的链接函数一起使用
angular.module('buttons',[])
.directive 'confirmable', () ->
template: """
<button class='btn btn-mini btn-danger'>
Destroy
</button>
"""
replace: yes
link: (scope, el, attrs) -> <---------- linking function
$(el).attr 'ng-click', attrs.ngClick
但是我再次浏览了指令文档,并找到了带有 =、@ 和 & 运算符的 scope 属性,但我真的不确定它们是否是我需要的。然后是这个 transclude 属性,我仍然需要了解它,但目前似乎也没有帮助。所以虽然我的链接函数现在可以解决问题,但我想我应该问一下 angular 是否提供了更优雅的解决方案。
谢谢!
最佳答案
在我看来,您想从指令中的父作用域调用方法...
我整理了一个 Plunk here
(对不起,我喜欢 JavaScript ......所以这里是)
这是您的父 Controller 。
app.controller('ParentCtrl', function($scope) {
$scope.fooCalled = 0;
$scope.foo = function() {
$scope.fooCalled++;
};
});
然后你的标记
<div ng-controller="ParentCtrl">
Foo Called: {{fooCalled}}<br/>
<button ng-click="foo()">Call From Parent</button><br/>
<custom-control custom-click="foo()"></custom-control>
</div>
以及您的指令声明:
app.directive('customControl', function(){
return {
restrict: 'E',
scope: {
innerFoo: '&customClick'
},
template: '<button ng-click="innerFoo()">Call From Control</button>'
};
});
scope
中的位指令定义中的声明将父作用域函数引用与指令的作用域联系起来,因此可以在单击时调用它。这就是&
是为了那里。
关于angularjs - angular.js : how to pass ngclick from original dom to directive's dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039983/