javascript - 为什么我不能在 AngularJS 链接函数中使用 vanilla javascript(事件监听器)?

标签 javascript angularjs angularjs-directive

所以我只是在测试一些东西,我正在写一个这样的指令:

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/

相关文章:

AngularJS - 基于表达式隐藏/显示指令输出

javascript - 元素宽度/高度是否可以小于最小宽度/最小高度?

javascript:var 在 mozilla 中是 'undefined',在 chrome 上有效

javascript - 我可以观察指令中属性的变化吗?

javascript - 如何在 Angular Js 中的类上编写指令?

javascript - Angularjs - $http 请求在函数内部不起作用

javascript - 带有响应的 CustomEvent,这可能吗?

javascript - 我可以依赖非链式后续 promise 订单吗?

angularjs - 在 Angular 中使用 aws-sdk-js 时“AWS 未定义”

javascript - 不同的 ng 模式行为