我正在尝试直接传递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);
});
}
};
});
这第二个例子有效。
我不明白为什么第一个例子被打破了。有什么想法吗?
修改 我忘了提,浏览器没有给我任何错误。它只是向我展示了一个空元素。
答案 0 :(得分:1)
实际上,这是因为angular的注入器会自动更改函数的this
属性,请考虑这一点:
var test = function(string) {
return {
html: function(value) {
console.log(this);
}
}
}
$scope.$watch('my_watch_expression', test('string').html);
当您检查this
的值时,您会得到以下内容:
如您所见,它会在jQuery
库上引发错误:
this
没有empty
函数,因此,它会抛出一个静默异常,并且不会按预期工作。
答案 1 :(得分:-1)
在官方文档中,https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ watch
$ watch中的第二个参数是监听器
"The listener is called only when the value ..."
逻辑上如果监听器被“调用”它必须是一个函数......或者我在这里错了。
当你这样做时:
link: function (scope, element, attrs) {
scope.$watch('someVariable', element.html); // <-- Passing the function handle as listener
}
它查看链接函数中传递的元素并尝试访问.html属性。它可能是一个函数,但它返回一个字符串...因此它成功运行,但不进行任何日志记录,因为等价物将是这样的:
scope.$watch('someVariable', "<div> some content </div>");
哪个不会做任何事情,但不会导致任何错误。
如果你把它包装在一个函数中,那么你可以用它做点什么。