Skip to main content
 首页 » 编程设计

javascript之将 jqLite .html() 句柄直接作为 AngularJS 监视监听器传递

2025年05月04日105xiaohuochai

我正在尝试将 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); 
      }); 
    } 
  }; 
}); 

第二个示例有效。

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

编辑: 我忘了说,浏览器没有给我任何错误。它只显示一个空元素。

请您参考如下方法:

其实是因为angular的注入(inject)器自动改变了函数的this属性,考虑一下:

var test = function(string) { 
    return { 
        html: function(value) { 
            console.log(this); 
        } 
    } 
} 
 
$scope.$watch('my_watch_expression', test('string').html); 

当您检查 this 的值时,您会得到以下结果:

如您所见,它会在 jQuery 库上抛出一个错误:

this 没有 empty 函数,因此,它将抛出静默异常并且不会按预期工作。