将jqLit​​e .html()句柄直接传递为AngularJS监听侦听器

时间:2014-11-12 18:05:54

标签: javascript angularjs jqlite

我正在尝试直接传递jqLit​​e函数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);
      });
    }
  };
});

这第二个例子有效。

我不明白为什么第一个例子被打破了。有什么想法吗?

修改 我忘了提,浏览器没有给我任何错误。它只是向我展示了一个空元素。

2 个答案:

答案 0 :(得分:1)

实际上,这是因为angular的注入器会自动更改函数的this属性,请考虑这一点:

var test = function(string) {
    return {
        html: function(value) {
            console.log(this);
        }
    }
}

$scope.$watch('my_watch_expression', test('string').html);

当您检查this的值时,您会得到以下内容:

enter image description here

如您所见,它会在jQuery库上引发错误:

enter image description here

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>"); 

哪个不会做任何事情,但不会导致任何错误。

如果你把它包装在一个函数中,那么你可以用它做点什么。