所以我只是在测试一些东西,我正在写一个这样的指令:
HTML
<div ng-app="app">
<my-directive>
hi {{name}}
</my-directive>
</div>
JS
angular.module("app", [])
.directive("myDirective", function () {
return {
scope:true,
restrict: "E",
link: function (scope, elem, attr) {
scope.name="yourname";
elem.onclick = function () { console.log("change name");}
}
}
})
但是 onclick 函数永远不会触发。而且我知道这不是我应该在 Angular 中正确编写的方式,但这只是我临时做的事情。但是,这有效:
angular.module("app", [])
.directive("myDirective", function () {
return {
scope:true,
restrict: "E",
link: function (scope, elem, attr) {
scope.name="yourname";
elem.on("click", function () {console.log("change name")});
}
}
})
这里有一个 fiddle :fiddle
这是怎么回事?它在 Angular 世界之外吗?我应该使用 scope.apply
或其他东西来让它工作吗?我很好奇为什么在这种情况下 vanilla javascript 不行。但这也是让我自己专注于以 Angular 方式思考的一个很好的教训。
也许有人可以解释发生了什么? 时间差
最佳答案
因为 elem
里面的 link 函数是一个 jQuery 对象。您应该使用 elem[0]
获取 html dom 元素,然后尝试。
angular.module("app", [])
.directive("myDirective", function () {
return {
scope:true,
restrict: "E",
link: function (scope, elem, attr) {
scope.name="yourname";
elem[0].onclick = function () { console.log("change name");}
}
}
})
关于javascript - 为什么我不能在 AngularJS 链接函数中使用 vanilla javascript(事件监听器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30603882/