我见过有些人在there指令的链接函数中绑定(bind)click而不是ng-click。
我研究了很久,没有找到答案。谁能给我一个理由吗?
我一直在使用 ng-click,因为它比创建新指令容易得多,而且我可以一目了然。
示例
我如何编写指令
HTML
<some-directive>
<button ng-click="someFunction()">Lorem Ipsum</button>
</some-directive>
Javascript
angular.module('myapp',[])
.directive('someDirective',function(){
return {
restrict:'E',
scope:{},
link: function (scope,element,attrs) {
//Code goes here
scope.someFunction = function() {
//callback
}
//More code goes here
}
}
})
大多数人如何编写指令
html
<some-directive>
<button click-trigger>Lorem Ipsum</button>
</some-directive>
Javascript
angular.module('myapp',[])
.directive('someDirective',function(){
return {
restrict:'E',
scope:{},
link: function (scope,element,attrs) {
//Code goes here
}
}
})
.directive('click-trigger',function($rootScope) {
return {
restrict:'E',
link: function(scope,element,attrs) {
element.bind('click',callBackFunction);
function callBackFunction () {
//callback
}
}
}
})
最佳答案
在我看来,更 Angular 方式是将嵌套元素包含在模板中。
.directive('foo', function(){
return {
template:'<button ng-click="clickMe()">Click Me</button>'
}
})
您的方法的问题是嵌套的 DOM 元素属于指令的范围 - 而不是 Controller 的范围。如果您尝试创建隔离范围,您很容易陷入困惑。
请注意,当涉及到隔离范围时, Angular 行为方式很奇怪。我认为这不必要地复杂。
请学习this问题。
关于javascript - AngularJS 在 Angular 指令中绑定(bind) click 相对于 ng-click 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35079436/