【发布时间】:2026-01-16 08:25:01
【问题描述】:
我正在尝试将 jqLite 函数 element.html 直接作为观察者的侦听器传递:
angular.module('testApp', []).directive('test', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('someVariable', element.html); // <-- Passing the function handle as listener
}
};
});
但是由于某种原因这不起作用,因此作为一种解决方法,我将侦听器包装在一个函数中:
angular.module('testApp', []).directive('test', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('someVariable', function (newValue) {
element.html(newValue);
});
}
};
});
第二个例子有效。
我不明白为什么第一个示例被破坏了。有什么想法吗?
编辑: 我忘了提,浏览器没有给我任何错误。它只是向我显示了一个空元素。
【问题讨论】:
-
是的,请阅读 $watch 文档docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch 监听器必须是一个函数而不是字符串或元素
-
你想实现什么传递元素 html?
-
据我了解
typeof element.html返回function,所以这应该没问题。我只是想省略包装功能,但很困惑为什么这不起作用。 -
该函数虽然返回一个字符串..所以它不会做任何事情...请参阅下面的解释。
标签: javascript angularjs jqlite